-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathprint-nth-to-last-node.py
55 lines (43 loc) · 1 KB
/
print-nth-to-last-node.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
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def reverse(head):
prev = None
cur = head
while cur != None:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev
def printntolast(val, head):
head = reverse(head)
cur = head
while val > 1:
cur = cur.next
val -= 1
return cur
###############################################
#### SOLUTION WITHOUT REVERSING
""" def ntolast(n, head):
left = head
right = head
for i in range(n):
if not right.next:
raise LookupError('ERROR: n is larger than list')
right = right.next
while right.next:
left = left.next
right = right.next
return left """
################################################
if __name__ == "__main__":
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)
a.next = b
b.next = c
c.next = d
print(printntolast(1, a).value)