One way linked list with Python

Keywords: Python Attribute less

Written in front

Recently, I was looking at the data structure. I found that only these things can make me understand the data types in python more deeply. In fact, no matter how the language changes, the data structure and algorithm are immutable. These things can be learned quickly by learning some other languages.
I may have been too busy. I looked at a list several times and covered my face manually,.

What is a linked list

As the name suggests, a list is a chain
Linked list is a kind of dynamic data structure, which is characterized by using a set of arbitrary storage units to store data elements. Every element in the list is called "node", and each node is composed of data field and pointer field. Unlike arrays, linked lists do not need to be pre-defined in size, and they can be expanded infinitely with hardware support.

Using python code to implement

The implementation of linked list is essentially independent of language. But flexibility is closely related to the language that implements it.
It's relatively simple to implement in python.
Define a node:

# The node of single chain table is composed of data field and pointer field. Generally speaking, it is an address to store data one by one.
class Node(object):
    '''node'''
    def __init__(self,element):
        # Save node data
        self.element = element 
        # The address of the next node. Because the linked list has not been created yet, and the next node point is still uncertain, the address of the next node is temporarily empty
        self.next = None 

After the node is created, a one-way linked list is created.

class SingleLinkList(object):
    '''Realize single chain table and connect nodes in series'''
    # Here, an object's attribute is implemented. The purpose is to hang the node to the beginning of the list, and the subsequent nodes will not get lost
    # At the beginning, the node is empty by default
    def __init__(self,node=None):
        self.__head = node

    def is_empty(self):
        '''Judge whether the list is empty'''
        # Empty if the head of the list has no nodes
        return self.__head == None

    def length(self):
        '''Return the length of the linked list'''
        # To know the length of a linked list, you need to traverse it once and count it
        # Define a cursor, point to the first node, and calculate the number of elements in the linked list by moving the cursor
        cur = self.__head # Represents that the cursor and the first node point to the same location
        count = 0
        while cur != None:
            count += 1
            cur = cur.next # Cursor movement
        return count

    def travel(self):
        '''Traverse the entire list'''
        cur = self.__head
        while cur != None:
            print(cur.element,end=' ')
            cur = cur.next

    def add(self,item):
        '''Add elements to the head'''
        # Add in the head, disconnect the original head node
        # The address of the new node points to the first location of the original node, and then the element of the new node is set as the header
        node = Node(item)
        node.next = self.__head
        self.__head = node
    def append(self,item):
        '''Add elements at the end of the list,Tail insertion method'''
        # Construct this node first
        node = Node(item)
        if self.is_empty():
            self.__head = node
        else:
            cur = self.__head
            # Please note that the judgment conditions have changed
            while cur.next != None:
                cur = cur.next
            cur.next = node

    def insert(self,pos,item):
        '''Insert element at specified location'''
        # If the position element entered is less than zero, insert it in the header
        if pos <= 0:
            self.add(item)
        # If the location element entered is greater than the length of the list, insert at the end
        elif pos > (self.length()-1):
            self.append(item)
        else:
            node = Node(item)
            pre = self.__head
            count = 0
            # To operate on the previous element of the insertion location
            while count < (pos - 1):
                pre = pre.next
                count += 1
            # When the loop exits, pre points to pos-1.
            node.next = pre.next
            pre.next = node

    def remove(self,item):
        '''Delete node'''
        pass
    def search(self,item):
        '''Find whether the node exists'''
        cur = self.__head
        while cur != Node:
            if cur.element == item:
                return True
            else:
                cur = cur.next
        return False




if __name__ == '__main__':
    li = SingleLinkList()
    print('Is it empty?',li.is_empty())
    print('Is the length 0',li.length())
    li.append(1)
    print('Is it empty?',li.is_empty())
    print('Is the length 0',li.length())
    li.append(2)
    li.add(9)
    li.travel()
    li.insert(1,10)
    li.travel()

Posted by sahammondsr on Sun, 15 Dec 2019 08:33:28 -0800