-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion_5.py
More file actions
61 lines (52 loc) · 1.64 KB
/
question_5.py
File metadata and controls
61 lines (52 loc) · 1.64 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
58
59
60
61
# Question 5
# Find the element in a singly linked list that's m elements from the end.
# For example, if a linked list has 5 elements, the 3rd element from the end
# is the 3rd element. The function definition should look like question5(ll, m),
# where ll is the first node of a linked list and m is the "mth number from the end".
# You should copy/paste the Node class below to use as a representation of a node in
# the linked list. Return the value of the node at that position.
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the begining of the Linked LinkedList
def push(self, new_value):
new_node = Node(new_value)
new_node.next = self.head
self.head = new_node
def nthFromLast(ll, m):
if m < 1:
return None
main_pointer = ll.head
ref_pointer = ll.head
count = 0
if(ll.head is not None):
while(count < m):
if(ref_pointer is None):
return None
ref_pointer = ref_pointer.next
count += 1
while(ref_pointer is not None):
main_pointer = main_pointer.next
ref_pointer = ref_pointer.next
return main_pointer.value
llist = LinkedList()
llist.push(40)
llist.push(35)
llist.push(78)
llist.push(5)
llist.push(89)
llist.push(124)
llist.push(400)
llist.push(22)
llist.push(1000)
print llist.nthFromLast(1)
# 40
print llist.nthFromLast(0)
# None
print llist.nthFromLast(23)
# None