-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01_doubly_linked_list.py
52 lines (42 loc) · 1.09 KB
/
01_doubly_linked_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
new_node.prev = None
self.head = new_node
else:
cur = self.head
while cur.next:
cur = cur.next
cur.next = new_node
new_node.prev = cur
new_node.next = None
def prepend(self, data):
new_node = Node(data)
if self.head is None:
new_node.prev = None
self.head = new_node
else:
self.head.prev = new_node
new_node.next = self.head
self.head = new_node
new_node.prev = None
def print_list(self):
cur = self.head
while cur:
print(cur.data)
cur = cur.next
dllist = DoublyLinkedList()
dllist.prepend(0)
dllist.append(1)
dllist.append(2)
dllist.append(3)
dllist.append(4)
dllist.print_list()