Python implementation of single linked list

Keywords: Python data structure linked list

The first is the representation of nodes in Python

Similar to C language, C language is represented by structs, while Python is represented by classes
1. Use class to represent nodes
class ListNode(object):
    def __init__(self,val,next = None):
        self.val = val                        #Data domain
        self.next = next                      #Pointer field

This class contains the data field and pointer field. The data field val is the value of the current node, and the pointer field next is the pointer to the next node.

2. Use tail interpolation to create a node
    def Creat(self,n):                        #Create linked list
        head = []                             #Use a list to store nodes
        for i in range(n):
            head.append(ListNode(i))          #Create linked list by tail insertion
        for i in range(n-1):
            head[i].next = head[i+1]          #Linked list
        return head                           #Return header node

head is a list used to store nodes. n is the number of incoming nodes. The first for loop calls the ListNode class to create the node, and uses the append method to store the newly built node at the end of the list. The second for loop makes the pointer field of the previous node point to the next node, and the two for loops realize the creation of linked list.

3. Print linked list
    def Printf(self,head):                    #Print linked list
        while head is not None:
            print(head.val)                   #Data field of output node
            head = head.next

As long as the next node is not empty, the data field of each node will be printed continuously.

4. Insert the element at the specified position
       def Insert(self,value,n,node):            #Inserts an element at the specified location
        if n < len(node):                     #Judge whether the specified position inserted is legal
            node.insert(n, ListNode(value))
            for i in range(len(node) - 1):
                node[i].next = node[i + 1]    # Reconnect nodes after insertion
            return node
        else:
            print("The inserted position is illegal")

The parameters passed in are value, n is the specified location, and node is the list of storage nodes. First, you need to judge whether the insertion position is legal. If n > the length of the linked list is not legal, output a prompt. If the insertion location is legal, call the ListNode class to create a node and insert it to the specified location with the insert method. Note that the above operation does not connect the newly established node to the original linked list. A for loop is needed to reconnect the linked list.

5. Insert the element at the specified position
    def Deleta(self, n, node):                #Deletes the element at the specified location
        if n < len(node):                     #Determine whether the insertion position is legal
            node.pop(n)
            for i in range(len(node) - 1):
                node[i].next = node[i + 1]    #Reconnect nodes after deletion
            return node
        else:
            print('The deleted location is illegal')

For the passed in parameter, n is the specified location, and node is the list of storage nodes. First, judge whether the deleted specified location is legal, that is, judge the relationship between the location index and the length of the linked list. If it is illegal, the prompt is output. If it is legal, the pop method is called to delete the node at the specified location. Note that after deleting the node, the original linked list is disconnected from this location, and an ffor cycle is needed to reconnect the linked list.

6. Number of output linked list nodes
    def CoundNodes(self,head):                #Number of output linked list nodes
        cnt = 0                               #The number of nodes is initialized to 0
        while head is not None:               #As long as the next node is not empty
            cnt += 1
            head = head.next                  #Node backward
        return cnt                            #Returns the number of nodes

The passed in parameter head is the list of storage linked list nodes. cnt is initialized to 0 to record the number of nodes. In the while loop, as long as the subsequent nodes of the linked list are not empty, the number of nodes will be increased by 1, and finally the number of nodes will be returned.

Complete code

class ListNode(object):
    def __init__(self,val,next = None):
        self.val = val                        #Data domain
        self.next = next                      #Pointer field
#Number of linked list nodes
class Solution():
    def Creat(self,n):                        #Create linked list
        head = []                             #Use a list to store nodes
        for i in range(n):
            head.append(ListNode(i))          #Create linked list by tail insertion
        for i in range(n-1):
            head[i].next = head[i+1]          #Linked list
        return head                           #Return header node

    def CoundNodes(self,head):                #Number of output linked list nodes
        cnt = 0                               #The number of nodes is initialized to 0
        while head is not None:               #As long as the next node is not empty
            cnt += 1
            head = head.next                  #Node backward
        return cnt                            #Returns the number of nodes

    def Printf(self,head):                    #Print linked list
        while head is not None:
            print(head.val)                   #Data field of output node
            head = head.next

    def Insert(self,value,n,node):            #Inserts an element at the specified location
        if n < len(node):                     #Judge whether the specified position inserted is legal
            node.insert(n, ListNode(value))
            for i in range(len(node) - 1):
                node[i].next = node[i + 1]    # Reconnect nodes after insertion
            return node
        else:
            print("The inserted position is illegal")

    def Deleta(self, n, node):                #Deletes the element at the specified location
        if n < len(node):                     #Determine whether the insertion position is legal
            node.pop(n)
            for i in range(len(node) - 1):
                node[i].next = node[i + 1]    #Reconnect nodes after deletion
            return node
        else:
            print('The deleted location is illegal')

if __name__ == '__main__':
    node = Solution().Creat(7)                #Create a linked list of 7 nodes
    Solution().Printf(node[0])                #Print linked list
    print('--------')
    node = Solution().Insert(520,3,node)      #Insert 520 in position 4
    Solution().Printf(node[0])
    print('--------')
    node = Solution().Deleta(5,node)          #Delete node at position 6
    Solution().Printf(node[0])
    print(f'Number of nodes:{Solution().CoundNodes(node[0])}')

2021.10.03.LN

Posted by zampu on Wed, 06 Oct 2021 23:48:04 -0700