-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial.py
More file actions
163 lines (96 loc) · 2.09 KB
/
Copy pathtutorial.py
File metadata and controls
163 lines (96 loc) · 2.09 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
class Node:
def __init__(self, data = None, next = None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def length(self):
count = 0
if self.head is None:
return 0
itr = self.head
while itr:
count += 1
itr = itr.next
return count
def insertAt(self, data, index):
if index < 0 or index > self.length():
print("Index out of range")
return
if index == 0:
self.insertAB(data)
count = 0
itr = self.head
while itr:
if count == index - 1:
node = Node(data, itr.next)
itr.next = node
count += 1
itr = itr.next
def insert(self, data):
NewNode = Node(data, None)
if self.head is None:
self.head = NewNode
itr = self.head
while itr.next:
itr = itr.next
itr.next = NewNode
def insertAB(self, data):
node = Node(data, self.head)
self.head = node
def insertValues(self, data):
self.head = None
for i in data:
self.insert(data)
def remove(self, index):
if self.head is None:
print("Linked List is empty, nothing to remove!")
if index == 0:
self.head = self.head.next
if index < 0 or index > self.length():
print("Index out of range")
return
count = 0
itr = self.head
while itr:
if count == index - 1:
itr.next = itr.next.next
count += 1
itr = itr.next
def print(self):
if self.head is None:
print("Linked List is empty")
return
itr = self.head
llstr = ''
while itr:
llstr += str(itr.data)
if itr.next != None:
llstr += ' --> '
itr = itr.next
print(llstr)
if __name__ == '__main__':
ll = LinkedList()
ll.insertAB(5)
ll.insertAB(16)
ll.insertAB(37)
ll.insertAB(19)
ll.insert(50)
# ll.insertValues(["mangoes", "oranges", "bananas", "grapes"])
ll.print()
print(ll.length())
ll.remove(3)
ll.print()
ll.insertAt(28, 0)
ll.print()
ll.insertAt(44, 3)
ll.print()
ll.insert(67)
ll.print()
ll.insertAt(100, 4)
ll.print()
print(ll.length())
ll.remove(2)
ll.print()
print(ll.length())