Python数据结构--双向链表

 1 '''
 2 双向链表包含第一个和最后一个的链接元素。
 3 每个链接都有一个数据字段和两个称为next和prev的链接字段。
 4 每个链接都使用其下一个链接与其下一个链接链接。
 5 每个链接都使用其上一个链接与之前的链接链接。
 6 最后一个链接将链接作为空来标记列表的结尾。
 7 '''
 8 
 9 
10 # 创建节点
11 class Node():
12     def __init__(self, data):
13         self.data = data
14         self.next = None
15         self.prev = None
16 
17 
18 # 创建双链表
19 class doubly_linked_list():
20     def __init__(self):
21         self.head = None
22 
23     # 遍历链表
24     def listprint(self, node):
25         while node:
26             print(node.data)
27             # last = node
28             node = node.next
29 
30     # 在头部添加新节点
31     def push(self, NewVal):
32         NewNode = Node(NewVal)
33         NewNode.next = self.head
34         if self.head:
35             self.head.prev = NewNode
36         self.head = NewNode
37 
38     # 在中间任意位置插入节点
39     def insert(self, prev_node, NewVal):
40         if prev_node is None:
41             return
42         NewNode = Node(NewVal)
43         NewNode.next = prev_node.next
44         prev_node.next = NewNode
45         NewNode.prev = prev_node
46         if NewNode.next:
47             NewNode.next.prev = NewNode
48 
49     # 在最后追加节点
50     def append(self, NewVal):
51         NewNode = Node(NewVal)
52         NewNode.next = None
53         if self.head is None:
54             NewNode.prev = None
55             self.head = NewNode
56             return
57         last = self.head
58         while last.next:
59             last = last.next
60         last.next = NewNode
61         NewNode.prev = last
62         return
63 
64 
65 dllist = doubly_linked_list()
66 dllist.push(12)
67 dllist.push(8)
68 dllist.append(20)
69 dllist.push(6)
70 dllist.insert(dllist.head.next, 10)
71 dllist.append(30)
72 dllist.listprint(dllist.head)
73 
74 # 结果 6 8 10 12 20 30
75 # 根据结果可知push是依次加到最前,无论append在什么位置,都是在最后追加

看图理解更容易:https://www.cnblogs.com/Knight-of-Dulcinea/p/9945821.html

03-看图理解数据结构与算法系列(双向链表)

posted @ 2018-11-20 15:24  浅尝辄止易初心不改难  Views(163)  Comments(0Edit  收藏  举报