-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.py
More file actions
113 lines (80 loc) · 2.6 KB
/
linked_list.py
File metadata and controls
113 lines (80 loc) · 2.6 KB
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
103
104
105
106
107
108
109
110
111
112
113
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self, array=None):
self.head = None
self.tail = None
if array:
for element in array:
self.append(element)
def push(self, new_data):
# Creates new node
new_node = Node(new_data)
# Makes current head as new node's next
new_node.next = self.head
# Makes the head as the tail
self.tail = self.head
# Makes new node the current head
self.head = new_node
return new_node
def insertAfter(self, prev_node, new_data):
# Check whether the previous node is None
if prev_node is None:
print("The previous node is empty")
return
# Creating new node
new_node = Node(new_data)
# if prev_node.next is None:
if prev_node == self.tail:
# Makes the new node as the tail
self.tail = new_node
else:
# Making the previous node's next as the new node's next
new_node.next = prev_node.next
# Making the new node as the previous node's next
prev_node.next = new_node
return new_node
def append(self, new_data):
# Create the new node
new_node = Node(new_data)
# If the Linked List is empty, makes new node as the head
if self.head is None:
self.head = new_node
self.tail = new_node
return new_node
self.tail.next = new_node
self.tail = new_node
return new_node
def nthNode(self, position):
if position >= self.getLength() or position < 0:
print("The position % 2d is out of bounds")
return None
count = 0
current = self.head
while (current):
if count == position:
return current
count += 1
current = current.next
def getLength(self):
length = 0
current = self.head
while (current):
length += 1
current = current.next
return length
def deletePosition(self, position):
nth_node = self.nthNode(position)
# If nth node is head, updates head
if nth_node == self.head:
self.head = nth_node.next
return nth_node
prev_node = self.nthNode(position - 1)
if nth_node == self.tail:
self.tail = prev_node
prev_node.next = nth_node.next
return nth_node
def deleteKey(self, key):
pass