Definition of a linked list:
A linked list (linked list) is a data structure consisting of a set of data elements called nodes, each of which contains information about the node itself and the address that points to the next node . Since each node contains address information that can be linked, a variable can be used to access the entire sequence of nodes. In other words, the node contains two pieces of information: the value that is used to store the data element , called the information field , and a pointer to store the address of the next data element , called the pointer field . The address of the first node in the list is stored in a separate node , called the head node or the first node. The last node in the list has no successor element , and its pointer field is empty.
#!/usr/bin/python#-*-coding:utf-8-*-classNode (object):def __init__(self,val,p=0): Self.data=Val Self.next=Pclasslinklist (object):def __init__(self): Self.head=0def __getitem__(self, key):ifself.is_empty ():Print 'linklist is empty.' return elifKey <0orKey >self.getlength ():Print 'The given key is error' return Else: returnSelf.getitem (Key)def __setitem__(self, Key, value):ifself.is_empty ():Print 'linklist is empty.' return elifKey <0orKey >self.getlength ():Print 'The given key is error' return Else: Self.delete (key)returnSelf.insert (Key)definitlist (self,data): Self.head=Node (data[0]) p=Self.head forIinchData[1:]: node=Node (i) P.next=Node P=P.nextdefGetLength (self): P=self.head Length=0 whilep!=0:length+=1P=P.nextreturnlengthdefIs_empty (self):ifSelf.getlength () = =0:returnTrueElse: returnFalsedefClear (self): Self.head=0defAppend (self,item): Q=Node (item)ifSelf.head = =0:self.head=QElse: P=Self.head whilep.next!=0:p=P.next P.next=QdefGetItem (self,index):ifself.is_empty ():Print 'linklist is empty.' returnJ=0 P=Self.head whileP.next!=0 andJ <index:p=P.next J+=1ifj = =Index:returnP.dataElse: Print 'target is not exist!' defInsert (Self,index,item):ifSelf.is_empty ()orIndex<0orIndex >self.getlength ():Print 'linklist is empty.' return ifindex = =0:q=Node (item,self.head) Self.head=Q P=Self.head Post=Self.head J=0 whileP.next!=0 andj<Index:post=P P=P.next J+=1ifindex = =J:q=Node (item,p) Post.next=Q Q.next=PdefDelete (self,index):ifSelf.is_empty ()orIndex<0orIndex >self.getlength ():Print 'linklist is empty.' return ifindex = =0:q=Node (item,self.head) Self.head=Q P=Self.head Post=Self.head J=0 whileP.next!=0 andj<Index:post=P P=P.next J+=1ifindex = =J:post.next=P.nextdefIndex (self,value):ifself.is_empty ():Print 'linklist is empty.' returnP=Self.head i=0 whileP.next!=0 and notP.data = =value:p=P.next i+=1ifP.data = =Value:returnIElse: return-1L=linklist () l.initlist ([1,2,3,4,5])PrintL.getitem (4) L.append (6)PrintL.getitem (5) L.insert (4,40)PrintL.getitem (3)PrintL.getitem (4)PrintL.getitem (5) L.delete (5)PrintL.getitem (5) L.index (5)
Implementation of single-link list of python--data structure