-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathSingly-Linked-List.py
76 lines (69 loc) · 1.49 KB
/
Singly-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
69
70
71
72
73
74
75
76
"""
------------------------ Singly Linked List -------------------------
"""
class node:
def __init__(self, data = None):
self.data = data
self.next = None
class singly_linked_list:
def __init__(self):
self.head = node()
def append(self, data):
new_node = node(data)
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = new_node
def length(self):
cur = self.head
count = 0
while cur.next != None:
count += 1
cur = cur.next
return count
def display(self):
elements = []
cur = self.head
while cur.next != None:
cur = cur.next
elements.append(cur.data)
return elements
def get(self, index):
if index >= self.length():
return "ERROR : index out of range!"
idx = 0
cur = self.head
while cur.next != None:
cur = cur.next
if idx == index:
return cur.data
idx += 1
def delete(self, index):
if index >= self.length():
return "ERROR : index out of range!"
idx = 0
cur = self.head
while cur.next != None:
last_node = cur
cur = cur.next
if idx == index:
last_node.next = cur.next
return "Node Deleted"
idx += 1
def insert(self, index, value):
if index > self.length():
return "ERROR : index out of range!"
elif index == self.length():
self.append(value)
return "Node Added"
new_node = node(value)
idx = 0
cur = self.head
while cur.next != None:
last_node = cur
cur = cur.next
if idx == index:
last_node.next = new_node
new_node.next = cur
return "Node Added"
idx += 1