Likou Question Record---Use python to implement basic operations of linked lists


Preface

How to use python to implement the basic operations of linked lists, including the definition of nodes, the definition of linked lists, finding the length of the linked list, whether the linked list is empty, and a series of functions


提示:以下是本篇文章正文内容,下面案例可供参考

1. Use python to implement basic operations of linked lists

The nodes in the linked list should contain a value and an address pointing to the next element.

1. The definition of nodes is implemented using classes:

class Node():
    def __init__(self,elem):
        self.elem = elem
        self.next = None

Since everything in python is an object, variables are actually references to objects, which is equivalent to saving the address of the object.

1. The definition of linked list is implemented using classes:

The definition of linked list is as follows, which is also implemented using classes:

class Single_LinkList():
    def __init__(self,node = None):
        self.head = node

An empty linked list will be automatically generated during initialization, with head pointing to None.

3. Determine whether it is an empty function implementation:

    def is_empty(self):
        """链表是否为空"""
        if self.head == None:
            return True
        else:
            return False

4. Implementation of linked list length function:

    def length(self):
        """链表长度"""
        len = 0
        cur = self.head
        while cur != None:
            len = len + 1
            cur = cur.next
        return len

5. Implementation of linked list traversal function:

    def travel(self):
        """遍历链表"""
        cur =  self.head
        while cur != None:
            print(cur.elem)
            cur = cur.next

6. Head interpolation function implementation:

    def add(self,item):
        """链表头部进行添加元素"""
        node = Node(item)
        node.next = self.head
        self.head = node

7. Implementation of tail interpolation function:

    def append(self,item):
        """链表尾部进行添加元素"""
        node = Node(item)
        cur = self.head
        if self.is_empty():
            self.head = node
        else:
            while cur.next != None:
                cur = cur.next
            cur.next = node
            node.next = None

8. Insert value function implementation at the specified position in the linked list:

    def insert(self,pos,item):
        """
        在指定位置上添加元素
        :param pos: 从0开始
        :param item:
        :return:
        """
        node = Node(item)
        count = 0
        cur = self.head
        while cur != None:
            if count == pos - 1:
                node.next = cur.next
                cur.next = node
                break
            cur = cur.next
            count = count + 1

9. Delete a certain value function implementation:

    def remove(self,item):
        """删除某一个节点"""
        cur = self.head
        count = 0
        if self.is_empty():
            print("删除失败")
        elif self.head.elem == item:
            self.head = self.head.next
        else:
            while cur.next != None:
                if cur.next.elem == item:
                    cur.next = cur.next.next
                    break
                cur = cur.next

10 Check whether a function implementation exists on a node:

    def search(self,item):
        """查看某个节点是否存在"""
        cur = self.head
        while cur != None:
            if cur.elem == item:
                return True
            cur = cur.next
        return False

The complete code is as follows:

class Node():
    def __init__(self,elem):
        self.elem = elem
        self.next = None

class Single_LinkList():
    def __init__(self,node = None):
        self.head = node
    def is_empty(self):
        """链表是否为空"""
        if self.head == None:
            return True
        else:
            return False
    def length(self):
        """链表长度"""
        len = 0
        cur = self.head
        while cur != None:
            len = len + 1
            cur = cur.next
        return len
    def travel(self):
        """遍历链表"""
        cur =  self.head
        while cur != None:
            print(cur.elem)
            cur = cur.next
    def add(self,item):
        """链表头部进行添加元素"""
        node = Node(item)
        node.next = self.head
        self.head = node
    def append(self,item):
        """链表尾部进行添加元素"""
        node = Node(item)
        cur = self.head
        if self.is_empty():
            self.head = node
        else:
            while cur.next != None:
                cur = cur.next
            cur.next = node
            node.next = None
    def insert(self,pos,item):
        """
        在指定位置上添加元素
        :param pos:0开始
        :param item:
        :return:
        """
        node = Node(item)
        count = 0
        cur = self.head
        while cur != None:
            if count == pos - 1:
                node.next = cur.next
                cur.next = node
                break
            cur = cur.next
            count = count + 1
    def remove(self,item):
        """删除某一个节点"""
        cur = self.head
        count = 0
        if self.is_empty():
            print("删除失败")
        elif self.head.elem == item:
            self.head = self.head.next
        else:
            while cur.next != None:
                if cur.next.elem == item:
                    cur.next = cur.next.next
                    break
                cur = cur.next
    def search(self,item):
        """查看某个节点是否存在"""
        cur = self.head
        while cur != None:
            if cur.elem == item:
                return True
            cur = cur.next
        return False

The test code is as follows:

if __name__ == "__main__":
    Linklist = Single_LinkList()
    print(Linklist.is_empty())
    print(Linklist.length())
    print(Linklist.append(1))
    print(Linklist.is_empty())
    print(Linklist.length())
    print(Linklist.append(2))
    print(Linklist.append(3))
    print(Linklist.append(4))
    print(Linklist.append(5))
    Linklist.add(8)
    Linklist.insert(1,10)
    Linklist.remove(8)
    # Linklist.remove(8)
    Linklist.travel()
    print(Linklist.search(1))

The result is as follows:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_47250738/article/details/132000307