-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsingly_linked_list.py
More file actions
65 lines (58 loc) · 1.64 KB
/
singly_linked_list.py
File metadata and controls
65 lines (58 loc) · 1.64 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
class Node:
def __init__(self, data):
self.data = data
self.next=None
class SinglyLinkedList:
def __init__(self):
self.head = Node(None)
def append(self, data):
newNode = Node(data)
currentNode = self.head
while(currentNode.next != None):
currentNode = currentNode.next
currentNode.next = newNode
print(str(data) + ' was appended')
def prepend(self, data):
newNode = Node(data)
newNode.next = self.head.next
self.head.next = newNode
print(str(data) + ' was prepended')
def addByPosition(self, data, position):
if(position > self.length()):
print('Position out of range')
return
newNode = Node(data)
currentNode = self.head
for i in range(position-1):
currentNode = currentNode.next
print(str(data) + ' was added to position ' +str(position))
newNode.next = currentNode.next
currentNode.next = newNode
def removeByPosition(self, position):
if(position > self.length()):
print('Position out of range')
return
currentNode = self.head
for i in range(position-1):
currentNode = currentNode.next
print(str(currentNode.next.data) + ' was removed was removed from position ' + str(position))
currentNode.next = currentNode.next.next
def length(self):
length=0
currentNode = self.head
while not(currentNode.next == None):
currentNode = currentNode.next
length+=1
return length
def display(self):
if(self.head.next == None):
print('List is empty')
return []
else:
elements=[]
print('The list is : ')
currentNode = self.head
while not(currentNode.next == None):
currentNode = currentNode.next
elements.append(currentNode.data)
print(elements)