Python implements double linked list and circular linked list

Python implements linear table

Double linked list

The singly-linked list node has only one pointer to its successor, which makes the singly-linked list can only be traversed backwards sequentially from the first node. The time complexity of accessing the successor node is O(1), and the time complexity of accessing the predecessor node Is O(n).

Insert picture description here
The double-linked list just adds a prior pointer to its predecessor in the node of the singly-linked list. Therefore, the operations of performing a value lookup and a bitwise lookup in a doubly-linked list are the same as those of a singly-linked list. However, the implementation of insert and delete operations in a double-linked list is quite different from that of a singly-linked list. This is because the prior pointer needs to be modified when the "chain" changes, and the key is to ensure that the chain is constantly being modified during the modification process. In addition, the doubly-linked list can easily find its predecessor nodes. Therefore, the time complexity of the algorithm for inserting and deleting nodes is O(1).
The node definition of a doubly-linked list:

class linknode():#每个结点有两个数据成员,结点元素和指向下一个结点的指针
    def __init__(self,item):
        self.item=item
        self.next=None
		self.prior=None   

Insert node: insert the node
Insert picture description here pointed to by s after the node pointed to by p in the double-linked list, the execution code is:

s->next=p->next
s->prior=p
p->next->prior=s
p-next=s

Delete node Delete the node
Insert picture description here
pointed to by q in the double-linked list, and execute the code:

p->next=q->next
q->next->prior=p

Circular linked list

Circular singly linked
list The difference between a circular singly linked list and a singly linked list is that the pointer of the last node in the table is not NULL, but instead points to the head node, so that the entire linked list forms a ring.
Circular singly linked list
The next pointer of the end of the table points to the head node, so there is no node in the table whose pointer field is NULL, so the null condition of the circular singly linked list is:

Head node ->next==L? True:False


The difference between a circular double-linked list and a circular singly-linked list is that the priority pointer of the head node also points to the tail node, and the remaining nodes also have two pointer fields, and the priority points to its predecessor node.
Insert picture description here

When the circular double-linked list is empty, the priority and next of the head node are both equal to L

Guess you like

Origin blog.csdn.net/liulanba/article/details/113781488