forked from Minor-lazer/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplementation of singly linkedlist_Python.py
116 lines (104 loc) · 3.22 KB
/
implementation of singly linkedlist_Python.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
class Node:
def __init__(self,data):
self.data=data
self.next=None
class Linkedlist:
def __init__(self):
self.head=None
def lengthOfLinkedList(self):
currentnode=self.head
length=0
while currentnode is not None:
length+=1
currentnode=currentnode.next
return length
def isEmpty(self):
if self.lengthOfLinkedList()==0:
return True
else:
return False
def insertHead(self,newNode):
temp=self.head
self.head=newNode
self.head.next=temp
del temp
def insertEnd(self, newNode):
if self.head is None:
self.head=newNode
else:
lastnode=self.head
while True:
if lastnode.next is None:
break
lastnode=lastnode.next
lastnode.next=newNode
def insertAt(self,newNode,position):
if position<0 or position>self.lengthOfLinkedList():
print('You enter wrong position retarted person,FUCK OFF!!')
return
if position==0:
self.insertHead(newNode)
return
currentNode=self.head
currentpositon=0
while True:
if currentpositon==position:
prev.next=newNode
newNode.next=currentNode
break
prev=currentNode
currentNode=currentNode.next
currentpositon += 1
def deleteEnd(self):
lastnode=self.head
while lastnode.next is not None:
prev=lastnode
lastnode=lastnode.next
prev.next=None
def delethead(self):
if self.isEmpty() is False:
prevHead=self.head
self.head=self.head.next
prevHead.next=None
else:
print('List empty')
def deleteAt(self,position):
if position<0 or position>self.lengthOfLinkedList():
print('You enter wrong position retartdd person,FUCK OFF!!')
elif self.isEmpty() is False:
if position==0:
self.delethead()
return
currentNode=self.head
currentpos=0
while True:
if currentpos==position:
prev.next=currentNode.next
currentNode.next=None
break
prev=currentNode
currentNode=currentNode.next
currentpos+=1
def printLinkedlist(self):
if self.head is None:
print('Empty')
return
currentNode=self.head
while True:
if currentNode is None:
break
print(currentNode.data)
currentNode=currentNode.next
firstnode=Node('John')
linkedlist=Linkedlist()
linkedlist.insertEnd(firstnode)
secondnode=Node('Bem')
linkedlist.insertEnd(secondnode)
thirdnode=Node('Bikash')
linkedlist.insertHead(thirdnode)
fourthnode=Node('hello')
linkedlist.insertAt(fourthnode,2)
#linkedlist.deleteEnd()
linkedlist.deleteAt(2)
#linkedlist.delethead()
linkedlist.printLinkedlist()