-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathLinkedListNthToLastNode.py
More file actions
56 lines (47 loc) · 1.7 KB
/
Copy pathLinkedListNthToLastNode.py
File metadata and controls
56 lines (47 loc) · 1.7 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
# Linked list Nth to last node
# Author: Pradeep K. Pant, ppant@cpan.org
# Aim is a function that takes a head node and an integer value n and then
# returns the nth to last node in the linked list.
# First initialize singly linked list class
class LinkedListNode(object):
def __init__(self, value):
self.value = value
self.nextnode = None
def nth_to_last_node(n, head):
# Set variables
# Left pointer at head and right pointer at place nth distance from
# left pointer
# so we have blocks between left and right pointers we keep them moving
# till right pointer hits the tail
left_pointer = head
right_pointer = head
# setting up right pointer based on the val of n
for i in range(n - 1):
# Check edge cases
if not right_pointer.nextnode:
raise LookupError('Error: n is larger than linked list')
right_pointer = right_pointer.nextnode
# finally check if right pointer is hitting the tail if so return left pointer
while right_pointer.nextnode:
left_pointer = left_pointer.nextnode
right_pointer = right_pointer.nextnode
return left_pointer
# Test
# Create a Linked List
a = LinkedListNode(1)
b = LinkedListNode(2)
c = LinkedListNode(3)
d = LinkedListNode(4)
e = LinkedListNode(5)
a.nextnode = b
b.nextnode = c
c.nextnode = d
d.nextnode = e
print (f"a.nextnode: {a.nextnode.value}")
print (f"b.nextnode: {b.nextnode.value}")
print (f"c.nextnode: {c.nextnode.value}")
print (f"d.nextnode: {d.nextnode.value}")
# This would return the node d with a value of 4, because its the 2nd to last node.
target_node = nth_to_last_node(2, a)
print (f"Target node value (2nd to last): {target_node.value}")
# Ans: d=4