Python implements an unordered list: Linked list

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.