forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindNthNodeInLinkedList
63 lines (47 loc) · 1.18 KB
/
FindNthNodeInLinkedList
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
from sys import stdin
# Following is the Node class already written for the Linked List
class Node :
def __init__(self, data) :
self.data = data
self.next = None
def findNode(head, n) :
current = head # Initialise temp
count = 0 # Index of current node
while (current):
if (current.data == n):
return count
count += 1
current = current.next
return -1
def takeInput() :
head = None
tail = None
datas = list(map(int, stdin.readline().rstrip().split(" ")))
i = 0
while (i < len(datas)) and (datas[i] != -1) :
data = datas[i]
newNode = Node(data)
if head is None :
head = newNode
tail = newNode
else :
tail.next = newNode
tail = newNode
i += 1
return head
#to print the linked list
def printLinkedList(head) :
while head is not None :
print(head.data, end = " ")
head = head.next
print()
#main
try:
t = int(stdin.readline().rstrip())
while t > 0 :
head = takeInput()
i = int(stdin.readline().rstrip())
print(findNode(head,i))
t -= 1
except:
pass