Print ith node
For a given a singly linked list of integers and a position 'i', print the node data at the 'ith' position.
Note :
Input format :
Remember/Consider :
Output format :
Constraints :
Sample Input 1 :
Sample Output 1 :
Sample Input 2 :
Sample Output 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 | |
for i in arr: | |
if i==-1: | |
break | |
else: | |
NewNode=Node(i) | |
if head==None: | |
head=NewNode | |
tail=NewNode | |
else: | |
tail.next=NewNode | |
tail=NewNode | |
return head | |
def printLL(index,head): | |
c=0 | |
while head is not None: | |
if c==index: | |
return head.data | |
head=head.next | |
c=c+1 | |
for i in range(int(input())): | |
arr = list(map(int, input().split())) | |
index=int(input()) | |
if len(arr)>=index and arr.index(-1)>index: | |
print(printLL(index,LinkedLists(arr))) | |
else: | |
print() |
\\ this is a much shorter approach
ReplyDeleteclass Node{
public:
int data;
Node *next;
Node(int data){
this -> data = data;
this -> next = NULL;
}
};
void printIthNode(Node *head, int i) {
Node* current = head;
int count = 0;
while (current != NULL)
{
if (count == i)
cout << current->data;
count++;
current = current->next;
}