首页 > 编程 > Python > 正文

python 线性表的链式存储

2019-11-06 09:03:05
字体:
来源:转载
供稿:网友
最后一位插入有点问题
class Node(object):	def __init__(self,value,next=None):		self.value = value		self.next = nextclass LinkList(object):	def __init__(self):		self.head=0	def CreateList(n):		if n<0:			return False		if n==1:			return Node(1)		else:			root = Node(1)			tmp = root			for i in range (2,n+1):				tmp.next = Node(i)				tmp = tmp.next		return root	def PRintList(head):		p=head		while p!=None:			print p.value			p=p.next	def ListLen(head):		p=head		sum=0		while p!=None:			sum +=1			p=p.next	def insertList(head,n):		p=head		if n<1 or n>ListLen(head):			return		for i in range(1,n-1):			p=p.next		a=input("please input a value:  ")		print a		t=Node(value=a)		t.next=p.next		p.next=t		return head	def deleteList(head,n):		if n<1 or n>ListLen(head):			return		elif n is 1:			head = head.next		else:			p=head			for  i in range(1,n-1):				p=p.next			q=p.next			p.next = q.next			return headdef main():      # print "Create a linklist"      # head=CreateList(7)      # PrintList(head)      # print      # print "___________________________"        # n1=input("Enter the index to insert  ")      # n1=int(n1)    # print n1      # insertList(head,n1)      # PrintList(head)      # print      # print "___________________________"        # n2=input("Enter the index to delete   ")      # n2=int(n2)      # deleteList(head,n2)      # PrintList(head)      l=LinkList()    l.CreateList(7)  if __name__=='__main__':  main() 
#然而依旧没有好
class Node(object):	def __init__(self, value,p=0):		self.data = value		self.next = pclass LinkedList(object):	def __init__(self):		self.head = None	def getLength(self):		p = self.head		i = 0		while p!= None :			p=p.next			i+=1		print "length: %d " % i 		return i	def getItem(self,index):		p = self.head		j = 1		while p != None and j < index:			p=p.next			j+=1		# if p ==None or j > index:		# 	print 'p=None'		# 	return False		print "oo"		value = p.data		print "getItem:value= %d" %value		return value	def ListInsert(self,index,value):		p=self.head		j=1		while p != None and j < index:			p = p.next			j+=1		# if p ==None or j > index:		# 	return False		s=Node(value=value)		s.next=p.next		p.next=s		return p	def  ListDelete(self,index):		p=self.head		j=1		while p != None and j < index:			p = p.next			j+=1		if p ==None or j > index:			return False		q = p.next		p.next = q.next		return q.data	def ListInit(self,index):		p = self.head		L = Node(1,p=0)		for i in range(0,index):			value = input("please input value: ")			p = Node(value,L.next)			L.next = p			print 'p %s' % p.data		return p	def ListClear(self):		p = self.head		print 'p=none'		while p != None:			q = p.next			p.next = q.next			print " ListDelete"		return pif __name__ == '__main__':	l=LinkedList()	l.ListInit(3)	l.getLength()	#l.getItem(1)	l.ListClear()
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表