Python Data Structure-Implementation of linked lists

Source: Internet
Author: User

A linked list consists of a series of structures that do not need to be connected in the memory. These objects are sorted in linear order. Each structure contains table elements and pointers to subsequent elements. The pointer to the last unit points to NULL. To facilitate the delete and insert operations on the linked list, you can add a table header for the linked list.

 

The delete operation can be implemented by modifying a pointer.

The insert operation requires two pointer adjustments.

 

1. Implementation of one-way linked list

1.1 Node implementation

Each Node is divided into two parts. Some elements that contain a linked list can be called data fields. The other part is a pointer pointing to the next Node.

Class Node (): _ slots __= ['_ item',' _ next'] # define the Node instance attributes def _ init _ (self, item ): self. _ item = item self. _ next = None # the pointer of Node points to None def getItem (self) by default: return self. _ item def getNext (self): return self. _ next def setItem (self, newitem): self. _ item = newitem def setNext (self, newnext): self. _ next = newnext

1.2 Implementation of SinglelinkedList

Class SingleLinkedList (): def _ init _ (self): self. _ head = None # initialize the empty table self. _ size = 0

1.3 check whether the linked list is empty

def isEmpty(self):    return self._head==None   

1.4 add elements on the front end of the linked list

def add(self,item):    temp=Node(item)    temp.setNext(self._head)    self._head=temp

1.5 append add elements at the end of the linked list

Def append (self, item): temp = Node (item) if self. isEmpty (): self. _ head = temp # If the table is empty, set the added element to the first element else: current = self. _ head while current. getNext ()! = None: current = current. getNext () # current. setNext (temp) of the traversal chain table # current is the last element of the linked list.

1.6 whether search elements are in the linked list

def search(self,item):    current=self._head    founditem=False    while current!=None and not founditem:        if current.getItem()==item:            founditem=True        else:            current=current.getNext()    return founditem

1.7 position of index elements in the linked list

def index(self,item):    current=self._head    count=0    found=None    while current!=None and not found:        count+=1        if current.getItem()==item:            found=True        else:            current=current.getNext()    if found:        return count    else:        raise ValueError,'%s is not in linkedlist'%item  

1.8 remove delete an element from the linked list

def remove(self,item):    current=self._head    pre=None    while current!=None:        if current.getItem()==item:            if not pre:                self._head=current.getNext()            else:                pre.setNext(current.getNext())            break        else:            pre=current            current=current.getNext()

1.9 insert elements in the insert linked list

 def insert(self,pos,item):    if pos<=1:        self.add(item)    elif pos>self.size():        self.append(item)    else:        temp=Node(item)        count=1        pre=None        current=self._head        while count<pos:            count+=1            pre=current            current=current.getNext()        pre.setNext(temp)        temp.setNext(current)

All code

Class Node (): _ slots __= ['_ item',' _ next'] def _ init _ (self, item): self. _ item = item self. _ next = None def getItem (self): return self. _ item def getNext (self): return self. _ next def setItem (self, newitem): self. _ item = newitem def setNext (self, newnext): self. _ next = newnext class SingleLinkedList (): def _ init _ (self): self. _ head = None # initialize to an empty linked list def isEmpty (self): return self. _ head = None def size (self): curren T = self. _ head count = 0 while current! = None: count + = 1 current = current. getNext () return count def travel (self): current = self. _ head while current! = None: print current. getItem () current = current. getNext () def add (self, item): temp = Node (item) temp. setNext (self. _ head) self. _ head = temp def append (self, item): temp = Node (item) if self. isEmpty (): self. _ head = temp # If the table is empty, set the added element to the first element else: current = self. _ head while current. getNext ()! = None: current = current. getNext () # The current of the recurring list. setNext (temp) # current is the final element of the linked list def search (self, item): current = self. _ head founditem = False while current! = None and not founditem: if current. getItem () = item: founditem = True else: current = current. getNext () return founditem def index (self, item): current = self. _ head count = 0 found = None while current! = None and not found: count + = 1 if current. getItem () = item: found = True else: current = current. getNext () if found: return count else: raise ValueError, '% s is not in our list' % item def remove (self, item): current = self. _ head pre = None while current! = None: if current. getItem () = item: if not pre: self. _ head = current. getNext () else: pre. setNext (current. getNext () break else: pre = current. getNext () def insert (self, pos, item): if pos <= 1: self. add (item) elif pos> self. size (): self. append (item) else: temp = Node (item) count = 1 pre = None current = self. _ head while count <pos: count + = 1 pre = current. getNext () pre. setNext (temp) temp. setNext (current) if _ name __= = '_ main _': a = SingleLinkedList () for I in range (1, 10):. append (I) print. size (). travel () print. search (6) print. index (5). remove (4). travel (). insert (1, 4,100). travel ()

  

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.