-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsert LinkedList.py
64 lines (47 loc) · 1.22 KB
/
Insert LinkedList.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
__author__ = 'marina_senyutina'
"""
Insert Node at the end of a linked list
head pointer input could be None as well for empty list
Node is defined as
"""
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def Insert(self, data):
newNode = Node(data)
actualNode = self
while actualNode.next is not None:
actualNode = actualNode.next
actualNode.next = newNode
return self
def InsertNth(self, data, position):
if position == 0:
newNode = Node(data)
actualNode = self
newNode.next = actualNode
return self
else:
newnode = Node(data)
actualNode = self
n = 0
while n != position:
n += 1
actualNode = actualNode.next
nextNode = actualNode.next.next
actualNode.next = newnode
newnode.next = nextNode
return self
def print_list(self):
print(self.data)
if self.next == None:
print("Null")
else:
self.next.print_list()
l = Node()
l.Insert(1)
l.Insert(5)
l.print_list()
l.InsertNth(99,0)
print('------')
l.print_list()