Python implementation of the linked list code

Source: Internet
Author: User
This article mainly introduces the Python implementation of the link list instance code of the relevant information, the need for friends can refer to the following

Python implementation of linked list instance code

Objective

Algorithm and data structure is an immutable topic, as a programmer, mastering the common data structure implementation is very, very necessary.

Implementation checklist

Implementing a linked list is essentially irrelevant to the language. But flexibility is closely related to the language that implements it. Use Python today to implement this, including the following:

[' AddNode (self, data) '] [' Append (self, value) '] [' Prepend (self, value) '] [' Insert (self, Index, value) '] [' Delnode (self, Index) '] [' Delvalue (self, value) '] [' IsEmpty (self) '] [' Truncate (self) '] [' GetValue (self, Index) '] [' Peek (self) '] [' Pop (self) '] [' Reverse (self) '] [' Delduplecate (self) '] [' Updatenode (self, Index, value) '] [' Size (self) '] [' Print (self) ']

To generate such a list of methods must not be written manually, or more trouble ah, so I wrote a program to match these own methods of implementation. The code is simple, and the core idea is to match each line of the source file, find the content that matches the rule, and add it to the total result set.

The code is as follows:

# coding:utf8# @Author: Guo Pu # @File: getmethods.py                                 # @Time: 2017/4/5                  # @Contact: 1064319632@qq.com# @blog:/http/ blog.csdn.net/marksinoberg# @Description: Gets the list of all methods and parameters in a module or class import Redef parse (filepath, Repattern): with  Open (filepath, ' RB ') as F:    lines = F.readlines ()  # Pre-parse regular  rep = Re.compile (repattern)  # Create a list of result sets that hold methods and parameter lists  result = []  # begins a formal match implementation for the  lines:    res = re.findall (rep, str (line))    print ("{} match result {}". Format (str (line), res))    If Len (res)!=0 or res are not None:      result.append (res)    else:      continue  return [item for item in result if Item!=[]]if __name__ = = ' __main__ ':  repattern = ' Def (. [ ^_0-9]+\ (. *?\)): "  filepath = './singlechain.py '  result = Parse (filepath, repattern) for  item in result:    Print (str (item))

Linked list implementation

# coding:utf8# @Author: Guo Pu # @File: singlechain.py # @Time: 2017/4/5 # @ contact:1064319632@qq.com# @blog: http://blog.csdn.net/marksinoberg# @Description: Single-linked list implementation class Node (object): Def __  Init__ (self, data, next): Self.data = Data Self.next = Nextclass Lianbiao (object): Def __init__ (self): self.root = None # adds element node to single-linked list Def addNode (self, data): If Self.root==none:self.root = Node (data=data, Next=none) re Turn self.root Else: # with a head node, you need to traverse to the tail node and make the list increment operation cursor = Self.root while cursor.next!= none:curs or = Cursor.next cursor.next = node (data=data, Next=none) return Self.root # Add a new node at the end of the list, and the underlying call AddNode method to def a Ppend (self, Value): Self.addnode (data=value) # Add node in list header Def prepend (self, value): if Self.root = = None:self . root = node (value, none) Else:newroot = node (value, none) # Update Root Index newroot.next = self.root sel F.root = newroot # added at the specified position in the linked listNode def insert (self, Index, value): if Self.root = = None:return if index<=0 or index >self.size (): Print (' Index%d ' is illegal, you should look at the location of your insertion node throughout the list!      ') return elif index==1: # If index==1, add self.prepend (value) elif index = = self.size () + 1 in the header of the list: # If Index is more than the current list length, add the tail to Self.append (value) Else: # So, add a new node in the middle of the list and add it directly. Need to use counters to maintain insert unknown counter = 2 Pre = Self.root cursor = Self.root.next while cursor!=none:if count        ER = = Index:temp = Node (value, None) Pre.next = temp Temp.next = cursor break    Else:counter + = 1 PRE = cursor cursor = cursor.next # Delete node at specified location def delnode (self, Index):  if Self.root = = None:return if index<=0 or Index > self.size (): Return # The first position needs to be handled with care if index = = 1:self.root = Self.root.next Else:pre = self.root cursor = Pre.next counter = 2 while CU rsor!= NoNe:if index = = Counter:print (' can be here! ')  Pre.next = Cursor.next Break else:pre = cursor cursor = Cursor.next Counter + = 1 # Delete a linked list node element with value of values Def delvalue (self, value): if Self.root = = None:return # The first position needs to be handled with care if self.root. data = = Value:self.root = Self.root.next Else:pre = self.root cursor = Pre.next while Cursor!=non          E:if Cursor.data = = Value:pre.next = Cursor.next # Remember to update this node or there will be a dead loop ... cursor = Cursor.next Continue else:pre = cursor cursor = cursor.next # Determine if the linked list is empty def i Sempty (self): if self.root = = None or self.size () ==0:return True else:return False # Delete list and all elements inside def Truncate (self): if self.root = = None or self.size () ==0:return else:cursor = Self.root while cursor!   = None:cursor.data = None cursor = Cursor.next Self.root = None   cursor = None # Gets the value of the node at the specified location def getvalue (self, index): If Self.root is None or self.size () ==0:print (' The current list is empty! ') return None if Index<=0 or index>self.size (): Print ("Index%d is not legal!  "%index" return None else:counter = 1 cursor = Self.root while cursor was not none:if index = = Counter:return Cursor.data Else:counter + = 1 cursor = cursor.next # Gets the value of the tail of the linked list and does not delete  The tail node def peek (self): return Self.getvalue (Self.size ()) # Gets the value of the tail node of the linked list and removes the tail node def pop (self): if Self.root is None or Self.size () ==0:print (' The current list is empty!      ') return None elif self.size () ==1:top = Self.root.data Self.root = None return Top else:       Pre = Self.root cursor = Pre.next while Cursor.next was not none:pre = cursor cursor = Cursor.next top = Cursor.data Cursor = None Pre.next = None return Top # Single-linked list in reverse order to achieve def reverse (self): if the.     Root is None: return if Self.size () ==1:return else: # post = none pre = none cursor = Self.root while C        Ursor is not None: # print (' reverse order operations ') post = Cursor.next Cursor.next = Pre PRE = cursor cursor = post # Do not forget to assign the head node after the reverse order to root, otherwise it will not display correctly self.root = Pre # Delete duplicate elements in the list Def delduplecate (self): # using A map to store it, similar to the variant "bucket sort" dic = {} if Self.root = = None:return if self.size () = = 1:return pre = self.      Root cursor = Pre.next dic = {} # assign to Dictionary temp = self.root while Temp!=none:dic[str (temp.data)] = 0 temp = Temp.next temp = None # Start the operation of removing duplicate elements while cursor!=none:if dic[str (cursor.data)] = = 1:pre . Next = Cursor.next cursor = Cursor.next else:dic[str (cursor.data)] + = 1 pre = cursor CU Rsor = cursor.next # Modifies the value of the specified position node def updatenode (self, Index, value): if Self.root = = None:return if index< 0 or Index>self.size (): return If index = = 1:self.root.data = value return else:cursor = Self.root.next Counte R = 2 while cursor!=none:if counter = = Index:cursor.data = value break cursor = cur Sor.next counter + = 1 # Gets the size of the single-linked list def size (self): counter = 0 if Self.root = = None:return Counter E  Lse:cursor = Self.root while cursor!=none:counter +=1 cursor = cursor.next return counter         # Print List itself element def print (self): if (self.root==none): return else:cursor = Self.root while Cursor!=none: Print (cursor.data, end= ' \ t ') cursor = cursor.next print () if __name__ = = ' __main__ ': # Create a linked list object lianb Iao = Lianbiao () # Determines whether the current list is empty print ("The list is empty%d"%lianbiao.isempty ()) # Determines whether the current list is empty Lianbiao.addnode (1) Print ("The list is empty%d"%lian Biao.isempty ()) # Add some nodes for easy operation Lianbiao.addnode (2) Lianbiao.addnode (3) Lianbiao.addnode (4) Lianbiao.addnode (6) Lianbi Ao.addnode (5) Lianbiao.AddNode (6) Lianbiao.addnode (7) Lianbiao.addnode (3) # Print the current linked list all values print (' Print the current list of all values ') Lianbiao.print () # test the operation on the list for size Print ("Size of the list:" +str (Lianbiao.size ())) # Tests the acquisition of the specified location node value print (' Get the test specified location node value ') Print (Lianbiao.getvalue (1)) Print ( Lianbiao.getvalue (Lianbiao.size ())) Print (Lianbiao.getvalue (7)) # Test Delete the specified value in the linked list, repeatable delete print (' Test deleted list specified value, repeatable delete ') Lian Biao.delnode (4) Lianbiao.print () Lianbiao.delvalue (3) Lianbiao.print () # Remove duplicate elements from the list print (' Remove duplicate elements in linked list ') Lianbiao.del Duplecate () Lianbiao.print () # Specifies the location of the list element of the Update test print (' Update test of the list element at the specified location ') Lianbiao.updatenode (6,) Lianbiao.print () # Test Add node print (' Test on List Header Add node ') lianbiao.prepend (Lianbiao.prepend) (108) Lianbiao.print () # Test at the end of the linked list Add node print (' Test Add a node at the end of the list ') Lianbiao.append (lianbiao.append) lianbiao.print () # TEST Specifies the insert operation for subscript print (' test specified subscript insert operation ') lianbiao.in SERT (1, 10010) Lianbiao.insert (3, 333) Lianbiao.insert (Lianbiao.size (), 99999) Lianbiao.print () # test Peek operation print (' Test Peek operation ') print (Lianbiao.peek ()) Lianbiao.print () # test pop operation print (' Test pop operation ') print (Lianbiao.pop ()) Lianbiao.print () # test the reverse output of the single-linked list print (' Reverse order of test list Output ') Lianbiao.reverse () Lianbiao.print () # Test the truncate operation of the linked list print (' Truncate operation of the Test list ') lianbiao.truncate () Lianbiao.pri NT ()

What is the result of running the code? Whether we can meet our needs, and see the results of the printing:

D:\Software\Python3\python.exe e:/code/python/python3/commontest/datastructor/ singlechain.py list empty 1 linked list is empty 0 print current list all values 1  2  3  4  6  5 6 7 3  list  size: 9 test for a specified location node value 136 Test Delete the specified value in the list, repeatable delete can be here!1  2  3  6  5  6  7 3 1  2  6  5  6  7  Remove duplicate elements from linked list 1  2 6  5  7  update test for linked list element at specified location 1  2  6  5  7  Test Add a node to the list header 108 1  2  6  5  7  Test Add a node at the end of the list 108 1  2 6 5  7  99 100 Test Specify subscript insert Operation 10010  108 333 1  2  6 5  7  99999  100 Test Peek Operation 10010010  108 333 1  2  6  5  7  99999  100 Test pop operation 10010010  108 333 77 1  2  6  5  7  99999  test single-linked list reverse output 99999  7 5 6  2  1  77 333 108 10010  Test List truncate operation process finished with exit code 0

Just achieve the target demand.

Summarize

Today's content is still a comparative basis, there is no difficulty. But reading and writing is not the same thing, when it's OK to write such code is still very rewarding.

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.