What's the use of a linked list
Array: Advantages: The array elements can be accessed quickly through an index (array subscript); disadvantage: the insertion/deletion of elements requires an array of adjustments, inefficient;
List: Advantages: Insert/delete fast, and do not have to adjust the entire list; disadvantage: Only sequential access, not random access (like array subscript);
So, the list is used in some cases where it needs to be quickly inserted/deleted, but not too concerned or random access is required.
First create the Node class
Class Node:def __init__ (self,initdata): Self.data = Initdataself.next = Nonedef GetData (self): return self.datadef GetNext (self): return self.nextdef SetData (self,newdata): Self.data = Newdatadef Setnext (self,newnext): Self.next = Newnext
To create a class that operates on a linked list
Class Unorderedlist:def __init__ (self): Self.head = Nonedef isEmpty (self): Self.head = = nonedef Add (self,item): temp = Node (item) Temp.setnext (self.head) Self.head = tempdef size (self): current = Self.headcount = 0while Current! = None:count = Coun T + 1current = Current.getnext () return countdef search (self,item): current = Self.headfound = falsewhile Current! = None an D not found:if current.getdata () = = Item:found = Trueelse:current = Current.getnext () return founddef GetValue (self): Curre NT = Self.headcurrarr = []while Current! = None:currarr.append (Current.getdata ()) current = Current.getnext () return Currarrdef Remove (self,item): current = Self.headprevious = Nonefound = Falsewhile not found:if current.getdata () = = Item:f Ound = trueelse:previous = Currentcurrent = Current.getnext () if previous = = None:self.head = Current.getnext () Else:previo Us.setnext (Current.getnext ())
Python implements an unordered list: Linked list