Data structure and algorithm (python) - one-way linked list

A linked list consists of nodes and directed links. So we can generate two classes: node class and one-way linked list operation class.

Node class:

The node class is used to construct the nodes of the singly linked list, and a node contains two parts: value and pointing. (Assume that the node class is not directional, so the next parameter defaults to None)

class Node:
    def __init__(self, val, next=None):
        self.val = val    #将val传入的值赋给self.val
        self.next = next  #next始终为None,不具备指向性,在实例化时进行指向

The following is an example of instantiation:

Create node1 (val=1), node2 (val=2), and point node1 to node2.

node1 = Node(1)     # ①
node2 = Node(2)     # ②
node1.next = node2  # ③

 One-way linked list class:

When creating a singly linked list class, we must first create a head node, which only represents the beginning of a linked list, so no assignment is required.

1. Create a head node:

class LinkList:
    def __init__(self):
        self.head = Node(None)  # 通过之前的Node类创建一个链表的头结点

The following is an example of instantiation:

Create a singly linked list with a head and a node.

Idea: first generate a head node, a node, and then point the head node to the node.

l = LinkList()  # 用l将linklist实例化,之后l就具有了linklist所具有的属性
node = Node(1)  # 生成节点
l.head.next = node  # l.head就是生成的头节点:Node(none),图中用node_head表示
                    # .next表示将头节点指向node

From the above figure, how to find the node through the head node? —— How does l.head.next access the value of node? -l.head.next.val

 2. Convert the list to a linked list:

Idea: By accessing the list, add nodes to the values ​​in each list in a loop. We introduce a temporary variable p to represent the currently reached node. At the beginning p is at the head node, add node1 for the head node, then p moves to node1, adds node2 for node1, then p moves to node2, adds node3 for node2... until the elements of the list All added.

# 将列表转换为链表
def init_list(self, list_):
    p = self.head            # 将头节点赋给p 
    for item in list_:       # 循环遍历列表
        p.next = Node(item)  # 将下一个节点添加在当前节点(p)之后
        p = p.next           # 将p移动到下一个节点

3. Traverse the linked list and return the value

# 遍历列表并返回值
def show(self):
    p = self.head.next
    while p is not None:
        print(p.val)
        p = p.next

4. Clear all linked lists

Idea: Just set the next of the head node to None. Python will clean up the remaining data by itself.

# 清空全部链表
def clear(self):
    self.head.next = None

 5. Check if it is empty

# 检查链表是否为空
def is_empty(self):
    if self.head.next is None:
        return True
    else:
        return False

6. Insert

① Tail plugging method:

Idea: traverse p to the last node, and add a node after the last node

# 在链表末尾插入一个节点
def append(self, val):
    p = self.head
    while p.next is not None:
        p = p.next
    p.next = Node(val)

②Head insertion method:

Idea: Point the next node of the node to be inserted to the next node of the head node, and point the next node of the head node to this node.

def head_insert(self, val):
    node = Node(val)           # ①
    node.next = self.head.next # ②
    self.head.next = node      # ③

③ Random insertion method:

Idea: Introduce a temporary variable p to indicate the current node position. Move p to the position of index-1, and use the same idea as the head insertion method to insert.

# 在index处插入节点
def insert(self, index, val):
    p = self.head
    for i in range(index):
        if p.next is None:
            break
        p = p.next
    node = Node(val)
    node.next = p.next
    p.next = node

7. Pass in the node position and get the corresponding value

def get_index(self, index):
    p = self.head.next
    for i in range(index):
        if p.next is None:
            raise IndexError("list index is out of range")
        p = p.next
    return p.val

8. Delete node operation (delete by value)

def delete(self, x):
    p = self.head
    while p.next and p.next.val != x:
        p = p.next
    if p.next is None:
        raise ValueError("x is not found")
    else:
        p.next = p.next.next
    

 

Guess you like

Origin blog.csdn.net/weixin_45958695/article/details/128174502