-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathNthNodeFromEnd.py
67 lines (55 loc) · 1.22 KB
/
NthNodeFromEnd.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
#Node class
class Node(object):
"""docstring for Node"""
def __init__(self, data):
super(Node, self).__init__()
self.data = data
self.next = None
#Linked List class
class LinkedList(object):
"""docstring for LinkedList"""
def __init__(self):
super(LinkedList, self).__init__()
self.head = None
"""Inserting new node at the beginning"""
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
"""Print linked list"""
def printList(self):
if self.head == None:
print("List is empty!!!")
return
temp = self.head
while temp!=None:
print(temp.data,end=" ")
temp = temp.next
print()
def printNthfromEnd(self, n):
temp = self.head
nthnode = None
for i in range(n-1):
if temp:
temp = temp.next
while(temp):
if nthnode == None:
nthnode = self.head
else:
nthnode = nthnode.next
temp = temp.next
if(nthnode):
print(nthnode.data)
return nthnode
return None
if __name__ == '__main__':
llist=LinkedList()
llist.push(5)
llist.push(6)
llist.push(7)
llist.push(8)
llist.push(9)
llist.push(10)
llist.push(11)
llist.printList()
llist.printNthfromEnd(3)