This paper introduces the simple implementation method of Python single-linked list, and shares it for everyone's reference. Here's how:
In general, to define a single-linked list, you first define the list element: element. It contains 3 fields:
List: Identify which list you belong to
Datum: Change the value of the element
Next: The location of the next node
The specific implementation code is as follows:
Class LinkedList (object): Class Element (object): Def __init__ (self,list,datum,next): self._list = List Self._datum = Datum self._next = Next def getdatum (self): return self._datum Datum = Property (FG et = Lambda self:self.getDatum ()) def getNext (self): return Self._next Next = property (Fget = Lambda sel F:self.getnext ()) def __init__ (self): Self._head = None Self._tail = None def gethead (self): return Self._head Head = Property (Fget = Lambda Self:self.getHead ()) def prepend (self,item): tmp = self. Element (Self,item,self._head) if self._head is None:self._tail = tmp self._head = tmp def insert (self, POS , item): i = 0 p = self._head while P! = None and I < pos-1: p = p._next i + = 1 if p = = None or i > pos-1: return-1 tmp = self. Element (self, item, p._next) P._next = tmp return 1 def getItem (self, pos): i = 0 p = self._head while P! = NoNE and I < pos-1: p = p._next i + = 1 if p = = None or i > post-1: return-1 return p._datum de F Delete (self, pos): i = 0 p = self._head while P! = None and I < pos-1: p = p._next i + = 1 if P = = None or i > post-1: return-1 q = P._next P._nex = Q._next Datum = P._datum return Datum def SetI TEM (Self, POS, item): i = 0 p = self._head while P! = None and I < pos-1: p = p._next i + = 1 if p = = None or i > post-1: return-1 p._datum = Item return 1 def find (self, POS, item): i = 0 p = Self . _head while P! = None and I < pos-1: if p._datum = = Item:return 1 p = p._next i + = 1 ret Urn-1 def empty (self): if Self._head = = None:return 1 return 0 def size (self): i = 0 p = Self._head While P! = None and I < pos-1: p = p._next i + = 1 return i def clear (self): Self._head = None SE Lf._tail = Nonetest = LiNkedlist () test.prepend (' test0 ') print Test.insert (1, ' Test ') print Test.head.datumprint test.head.next.datum
Hopefully this article will help you with Python programming.