-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsll_operations.py
102 lines (83 loc) · 2.35 KB
/
sll_operations.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class SingleLL:
def __init__(self):
self.head = None
def len_ll(self):
counter = 0
if self.head is None:
return 0
else:
iterator = self.head
while iterator != None:
counter += 1
iterator = iterator.next
return counter
def insert_at_begin(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)
return
iterator = self.head
while iterator.next:
iterator = iterator.next
iterator.next = Node(data, None)
def insert_at_index(self, data, ind):
count = 0
iterator = self.head
while iterator:
if count == ind-1:
node = Node(data, iterator.next)
iterator.next=node
break
iterator= iterator.next
count+=1
def del_at_pos(self, idx):
if idx==0:
self.head = self.head.next
return
if idx>0 and idx<self.len_ll():
print("insice")
iterator = self.head
count=0
while iterator:
if count == idx-1:
iterator.next= iterator.next.next
break
iterator=iterator.next
count+=1
print(f"count {count}")
def print(self):
if self.head is None:
print("Linked List is empty")
return
iterator = self.head
list_str = " "
while iterator:
list_str += str(iterator.data) + "-->"
iterator = iterator.next
print(list_str)
if __name__ == "__main__":
list_1 = SingleLL()
list_1.insert_at_begin(45)
list_1.print()
list_1.insert_at_begin(50)
list_1.print()
list_1.insert_at_begin(60)
list_1.print()
list_1.insert_at_end(46)
list_1.print()
list_1.insert_at_end(34)
list_1.print()
list_1.insert_at_index(37,2)
list_1.print()
list_1.insert_at_index(37,0)
list_1.print()
list_1.del_at_pos(2)
list_1.print()
list_1.del_at_pos(0)
list_1.print()