forked from logicheap/DataStructures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListInsertion.py
More file actions
60 lines (45 loc) · 1.19 KB
/
LinkedListInsertion.py
File metadata and controls
60 lines (45 loc) · 1.19 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
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
def insertAtBeginning(self, data):
temp = Node(data)
temp.next = self.head
self.head = temp
def insertAfter(self, prev_node, data):
if prev_node is None:
print("Please provide a valid reference")
return
temp = Node(data)
temp.next = prev_node.next
prev_node.next = temp
def append(self, data):
temp = Node(data)
last_node = self.head
if self.head is None:
self.head = temp
while last_node.next :
last_node = last_node.next
last_node.next = temp
class Node:
def __init__(self, data):
self.data = data
self.next = None
ll = LinkedList()
firstNode = Node(10)
secondNode = Node(20)
thirdNode = Node(30)
fourthNode = Node(40)
ll.head = firstNode
firstNode.next = secondNode
secondNode.next = thirdNode
thirdNode.next = fourthNode
ll.printList()
ll.insertAtBeginning(5)
ll.insertAfter(ll.head.next.next.next, 5)
ll.append(5)
ll.printList()