forked from sarthakd999/Hacktoberfest2021-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.py
99 lines (82 loc) · 1.66 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
'''
* LinkedList.py
* Simple implementation of a Singly Linked List in python
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def traverse(self):
temp = self.head
data = []
while (temp):
data.append(temp.data)
temp = temp.next
return data
def search(self,item):
temp = self.head
i = 0
while (temp):
if(temp.data == item):
return {"data": temp.data, "position": i}
i += 1
temp = temp.next
return None
def length(self):
count = 0
temp = self.head
while (temp):
count += 1
temp = temp.next
return count
def insert_last(self,val):
newNode = Node(val)
if self.head == None:
self.head = newNode
else:
curr = self.head
while curr.next != None:
curr = curr.next
curr.next = newNode
def insert_first(self, val):
newNode = Node(val)
if self.head == None:
self.head = newNode
else:
newNode.next = self.head
self.head = newNode
def delete(self, val):
if self.head == None:
return None
else:
curr = self.head
prev = self.head
if self.head.data == val:
self.head = self.head.next
curr.next = None
else:
while curr != None and curr.data != val:
prev = curr
curr = curr.next
if curr != None:
prev.next = curr.next
curr.next = None
# Driver Code
def main():
List = LinkedList()
List.insert_last(1)
List.insert_last(2)
List.insert_last(3)
List.insert_last(4)
List.insert_last(5)
List.insert_last(6)
List.insert_first(0)
print(List.search(2))
print(List.traverse())
List.delete(0)
print(List.traverse())
if __name__ == '__main__':
main()