Python implements linked list instance code and python instance
Python implements linked list instance code
Preface
Algorithms and data structures are a constant topic. As a programmer, it is very necessary to master Common Data Structure implementations.
Implementation list
Implementing a linked list is essentially irrelevant to the language. However, flexibility is closely related to the language used to implement it. The following operations are implemented in Python today:
['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 method list, you must not manually write it. Otherwise, it would be much more troublesome. So I wrote a program to match these methods implemented by myself. The code is relatively simple. The core idea is to match each line of the source file, find the content that complies with the matching rules, and add it to the total result set.
The Code is as follows:
# Coding: utf8 # @ Author: Guo Pu # @ File: getmethods. py # @ Time: # @ Contact: 1064319632@qq.com # @ blog: http://blog.csdn.net/marksinoberg# @ Description: Get all methods and parameter lists in a module or class import redef parse (filepath, repattern ): with open (filepath, 'rb') as f: lines = f. readlines () # pre-parsed regular rep = re. compile (repattern) # create a result set list for the SAVE method and parameter list result = [] # Start the formal matching implementation for line in lines: res = re. findall (rep, str (line) ) Print ("{} matching result {}". format (str (line), res) if len (res )! = 0 or res is 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: # @ 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 # Add Element Node def addNode (self, data) to a single-chain table: if self. root = None: self. root = Node (data = data, next = No Ne) return self. root else: # if there is a header node, You need to traverse the end node and add the cursor = self. root while cursor. next in the linked list! = None: cursor = cursor. next cursor. next = Node (data = data, next = None) return self. root # Add a new node at the end of the linked list. The underlying layer can call the addNode method to def append (self, value): self. addNode (data = value) # Add node def prepend (self, value): if self. root = None: self. root = Node (value, None) else: newroot = Node (value, None) # update the root index newroot. next = self. root self. root = newroot # Add the node def insert (self, index, value) at the specified position of the linked list: if self. Root = None: return if index <= 0 or index> self. size (): print ('index % d is invalid. Check whether your inserted node is in the entire linked list! ') Return elif index = 1: # If index = 1, add self in the first part of the linked list. prepend (value) elif index = self. size () + 1: # If the index is exactly the same as the length of the current linked list, add it to the end to self. append (value) else: # in this case, add a new node to the center of the linked list and add it directly. You need to use counters to maintain the insertion of unknown counter = 2 pre = self. root cursor = self. root. next while cursor! = None: if counter = index: temp = Node (value, None) pre. next = temp. next = cursor break else: counter + = 1 pre = cursor. next # Delete the node def delNode (self, index) at the specified position: if self. root = None: return if index <= 0 or index> self. size (): return # Be careful when processing if index = 1: self. root = self. root. next else: pre = self. root cursor = pre. next counter = 2 while cursor! = None: if index = counter: print ('can be here! ') Pre. next = cursor. next break else: pre = cursor. next counter + = 1 # Delete the linked list node element def delValue (self, value): if self. root = None: return # Be careful when processing if self at the first position. root. data = value: self. root = self. root. next else: pre = self. root cursor = pre. next while cursor! = None: if cursor. data = value: pre. next = cursor. next # Remember to update this node. Otherwise, an endless loop will occur... Cursor = cursor. next continue else: pre = cursor. next # determine whether the linked list is empty def isempty (self): if self. root = None or self. size () = 0: return True else: return False # Delete the linked list and all its internal elements 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 # Get the value of the node at the specified position def getvalue (self, index): if self. root is None or self. size () = 0: print ('the current linked list is empty! ') Return None if index <= 0 or index> self. size (): print ("index % d is invalid! "% Index) return None else: counter = 1 cursor = self. root while cursor is not None: if index = counter: return cursor. data else: counter + = 1 cursor = cursor. next # Get the value at the end of the linked list and do not delete this tail node def peek (self): return self. getvalue (self. size () # obtain the value of the End Node of the linked list and delete the end node def pop (self): if self. root is None or self. size () = 0: print ('the current linked 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 is not None: pre = cursor. next top = cursor. data cursor = None pre. next = None return top # def reverse (self): if self. root is None: return if self. size () = 1: return else: # post = None pre = None cursor = self. root while cursor is no T None: # print ('reverse operation reverse operation ') post = cursor. next cursor. next = pre = cursor = post # Never forget to assign the header node in the reverse order to the root; otherwise, the self cannot be correctly displayed. root = pre # Delete the duplicate element def delDuplecate (self) in the linked list: # Use a map to store it, similar to the deformed "Bucket sorting" dic ={} if self. root = None: return if self. size () = 1: return pre = self. root cursor = pre. next dic ={}# assign temp = self to the dictionary. root while temp! = None: dic [str (temp. data)] = 0 temp = temp. next temp = None # Start to delete 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. next # modify the value of the specified 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 counter = 2 while cursor! = None: if counter = index: cursor. data = value break cursor = cursor. next counter + = 1 # obtain the size of a single-chain table def size (self): counter = 0 if self. root = None: return counter else: cursor = self. root while cursor! = None: counter + = 1 cursor = cursor. next return counter # print the Linked List's own 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 lianbiao = LianBiao () # determine whether the current linked list is empty print ("the linked list is empty % d" % lianbiao. isempty () # checks whether the current linked list is empty. addNode (1) print ("the linked list is empty % d" % lianbiao. isempty () # add some nodes to facilitate lianbiao operations. addNode (2) lianbiao. addNode (3) lianbiao. addNode (4) lianbiao. addNode (6) lianbiao. addNode (5) lianbiao. addNode (6) lianbiao. addNode (7) lianbiao. addNode (3) # print all values of the current linked list print ('print all values of the current linked list ') lianbiao. print () # test the size operation on the linked list print ("size of the linked list:" + str (lianbiao. size () # obtain the value of a specified node in the test print ('obtain the value of a specified node in the test ') print (lianbiao. getvalue (1) print (lianbiao. getvalue (lianbiao. size () print (lianbiao. getvalue (7) # test to delete the specified value in the linked list, and delete print repeatedly ('test to delete the specified value in the linked list, and delete it repeatedly ') lianbiao. delNode (4) lianbiao. print () lianbiao. delValue (3) lianbiao. print () # Remove duplicate elements in the linked list print ('remove duplicate elements from the linked list ') lianbiao. delDuplecate () lianbiao. print () # update test of linked list elements at the specified position print ('Update test of linked list elements at the specified position ') lianbiao. updateNode (6, 99) lianbiao. print () # test adding a node in the first part of the linked list print ('test adding a node in the first part of the linked list ') lianbiao. prepend (77) lianbiao. prepend (108) lianbiao. print () # test adding node print at the end of the linked list ('test adding node at the end of the linked list ') lianbiao. append (99) lianbiao. append (100) lianbiao. print () # test the insert operation print ('test the insert operation for the specified lower') lianbiao. insert (1, 10010) lianbiao. insert (3,333) lianbiao. insert (lianbiao. size (), 99999) lianbiao. print () # test the print ('test the peek operation') print (lianbiao. peek () lianbiao. print () # test the pop operation print ('test the pop operation') print (lianbiao. pop () lianbiao. print () # test the reverse output of a single-chain table print ('test the reverse output of a Single-Chain table') lianbiao. reverse () lianbiao. print () # test the chain table's truncate operation print ('test the chain table's truncate operation') lianbiao. truncate () lianbiao. print ()
What is the result of code execution? Whether it can meet our needs and check the printed results:
D: \ Software \ Python3 \ python.exe E:/Code/Python/Python3/CommonTest/datastructor/SingleChain. py linked list is empty 1 linked list is empty 0 print all values of the current linked list 1 2 3 4 6 5 6 7 3 linked list size: 9. Obtain the node value at the specified position. 136. Test: Delete the specified value in the linked list. You can also delete the value here! 1 2 3 6 5 6 7 3 1 2 6 5 6 7 remove duplicate elements in the Linked List 1 2 6 5 7 update test of elements in the linked list at the specified position 1 2 6 5 7 test on the linked list first add node 108 77 1 2 6 5 7 test add node 108 77 1 2 6 5 99 100 test specified downlink insert operation 10010 108 333 77 1 2 6 5 7 99 99999 100 test peek operation 10010010 108 333 77 1 2 6 5 7 99 99999 100 test pop operation 10010010 108 333 77 1 2 6 5 7 99 99999 test reverse output of a single-chain table 99999 99 7 5 6 2 1 77 333 108 10010 test the truncate operation of the linked list Process finished with exit code 0
The goal is met.
Summary
Today's content is still relatively basic and there are no difficulties. But there are two things to understand and write. It is very rewarding to write such code when nothing happens.