-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.py
101 lines (90 loc) · 2.51 KB
/
linkedlist.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
from sympy import EX
class Node:
def __init__(self,data=None,next=None):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert_at_beg(self,data):
node=Node(data,self.head)
self.head=node
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 else str(itr.data)
itr=itr.next
print(llstr)
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 insert_values(self,datalist):
self.head=None
for data in datalist:
self.insert_at_end(data)
def get_len(self):
count=0
itr=self.head
while itr:
count+=1
itr=itr.next
return count
def remove_at(self,index):
if index<0 or index>=self.get_len():
raise Exception("Invalid Index")
if index==0:
self.head=self.head.next
return
count=0
itr=self.head
while itr:
if count==index-1:
itr.next=itr.next.next
break
itr=itr.next
count+=1
def insert_at(self,index,data):
if index<0 or index>=self.get_len():
raise Exception("Invalid Index")
if index==0:
self.insert_at_beg(data)
return
count=0
itr=self.head
while itr:
if count==index-1:
node=Node(data,itr.next)
itr.next=node
break
count+=1
itr=itr.next
def insert_after_value(self,data_after,datanew):
itr=self.head
count=0
valExi=False
while itr:
if itr.data == data_after:
if count==self.get_len():
self.insert_at_end(datanew)
else:
self.insert_at(count+1,datanew)
valExi=True
break
itr=itr.next
count+=1
if not valExi:
raise Exception("Value not fount")
ll = LinkedList()
ll.insert_values(["banana","mango","grapes","orange"])
ll.print()
ll.insert_after_value("mango","apple") # insert apple after mango
ll.print()