-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
113 lines (100 loc) · 2.59 KB
/
main.py
File metadata and controls
113 lines (100 loc) · 2.59 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
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class linkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
node = Node(data, self.head)
self.head = node
def insert_at_end(self, data):
if self.head is None:
self.head = Node(data, None)
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data, None)
def list_len(self):
if self.head is None:
print('empty')
return
count = 0
itr = self.head
while itr:
count += 1
itr = itr.next
print(count)
def insert_list(self, data_list):
self.head = None
for items in data_list:
self.insert_at_end(items)
def remove_at(self, index):
if 0 > index >= self.list_len():
raise Exception('INVALID INDEX')
if index == 0:
self.head = self.head.next
return
itr = self.head
count = 0
while itr:
if count == index - 1:
itr.next = itr.next.next
break
itr = itr.next
count += 1
def insert_at(self, index, data):
if 0 > index >= self.list_len():
raise Exception('INVALID INDEX')
if index == 0:
self.insert_at_beginning(data)
itr = self.head
count = 0
while itr:
if count == index - 1:
node = Node(data, itr.next)
itr.next = node
break
itr = itr.next
count += 1
def remove_duplicate(self):
temp = self.head
if temp is None:
return
while temp.next is not None:
if temp.data == temp.next.data:
new = temp.next.next
temp.next = None
temp.next = new
else:
temp = temp.next
return self.head
def print(self):
if self.head is None:
print('list is empty')
return
itr = self.head
lst = ''
while itr:
lst += str(itr.data) + '-->'
itr = itr.next
print(lst)
ll = linkedList()
ll.insert_list([1, 2, 5, 6, 7])
ll.print()
ll.list_len()
ll.insert_at_beginning(45)
ll.insert_at_beginning(89)
ll.insert_at_end(56)
ll.print()
ll.list_len()
ll.remove_at(2)
ll.print()
ll.list_len()
ll.insert_at(2, 45)
ll.print()
ll.list_len()
ll.remove_duplicate()
ll.print()
ll.list_len()