forked from nishitpanchal395/projecthactoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linked list.py
68 lines (61 loc) · 1.63 KB
/
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
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):
n = Node(data,self.head)
self.head = n
def insert_at_end(self,data):
if self.head is None:
self.head = Node(data,self.head)
return
else:
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data,None)
def print(self):
if self.head is None:
print("Linked list is empty")
else:
itr = self.head
l=' '
while itr is not None:
l+= str(itr.data) + '-->'
itr = itr.next
print(l)
def get_length(self):
c=0
itr = self.head
while itr:
c+=1
itr=itr.next
return c
def remove_at(self,index):
if index<0 or index>=self.get_length():
print("Invalid Index")
elif index==0:
self.head = self.head.next
return
else:
c=0
itr=self.head
while itr:
if c==index-1:
itr.next=itr.next.next
break
itr=itr.next
c+=1
if __name__ == '__main__':
ll=LinkedList()
ll.insert_at_beginning(4)
ll.insert_at_beginning(7)
ll.insert_at_end(8)
ll.insert_at_end(2)
print(ll.get_length())
ll.print()
ll.remove_at(3)
ll.print()