Find a Node in Linked List
You have been given a singly linked list of integers. Write a function that returns the index/position of an integer data denoted by 'N'(if it exists). -1 otherwise.
Note :
Input format :
Remember/Consider :
Output format :
Constraints :
Sample Input 1 :
Sample Output 1 :
Sample Input 2 :
Sample Output 2 :
An explanation for Sample Input 2 :
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self,data): | |
self.data=data | |
self.next=None | |
def LinkedLists(arr): | |
head=None | |
tail=None | |
if len(arr)<1: | |
return -1 | |
else: | |
for i in arr: | |
if i is not -1: | |
NewNode=Node(i) | |
if head is None: | |
head=NewNode | |
tail=NewNode | |
else: | |
tail.next=NewNode | |
tail=NewNode | |
else: | |
break | |
return head | |
def printLL(head,n): | |
arr=[] | |
while head is not None: | |
arr.append(head.data) | |
head=head.next | |
if arr.__contains__(n): | |
print(arr.index(n)) | |
else: | |
print(-1) | |
for i in range(int(input())): | |
arr=list(map(int,input().split())) | |
n=int(input()) | |
printLL(LinkedLists(arr),n) |
Comments
Post a Comment
Please give us your valuable feedback