-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01_circular_linked_list.py
83 lines (61 loc) · 1.68 KB
/
01_circular_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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
self.head.next = self.head
cur = self.head
while cur.next != self.head:
cur = cur.next
cur.next = new_node
new_node.next = self.head
def prepend(self, data):
new_node = Node(data)
cur = self.head
new_node.next = self.head
if not self.head:
new_node.next = new_node
while cur.next != self.head:
cur = cur.next
cur.next = new_node
self.head = new_node
def remove(self, key):
if self.head.data == key:
cur = self.head
nxt = self.head.next
while cur.next != self.head:
cur = cur.next
cur.next = nxt
self.head = nxt
cur = None
else:
cur = self.head
prev = None
while cur.next != self.head:
prev = cur
cur = cur.next
if cur.data == key:
prev.next = cur.next
cur = cur.next
def print_list(self):
cur = self.head
while cur:
print(cur.data)
cur = cur.next
if cur == self.head:
break
cllist = CircularLinkedList()
cllist.append("A")
cllist.append("B")
cllist.append("C")
cllist.append("D")
cllist.print_list()
print("\n")
cllist.remove("B")
cllist.print_list()