-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path008_Node_at_given_Index.cpp
95 lines (75 loc) · 1.6 KB
/
008_Node_at_given_Index.cpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//{ Driver Code Starts
// C program to find n'th node in linked list
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
/* Link list node */
struct node
{
int data;
struct node* next;
node(int x){
data = x;
next = NULL;
}
};
struct node* push(struct node* head, int d)
{
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
new_node->data = d;
new_node->next = NULL;
if (head == NULL) return new_node;
struct node* h = head;
while (head->next != NULL) head = head->next;
head->next = new_node;
return h;
}
int GetNth(struct node* head, int index);
/* Driver program to test above function*/
int main()
{
int T,i,n,l,k;
cin>>T;
while(T--){
struct node *head = NULL;
cin>>n>>k;
for(i=1;i<=n;i++)
{
cin>>l;
head = push(head, l);
}
printf("%d\n", GetNth(head, k));
getchar();
}
return 0;
}
// } Driver Code Ends
/* Print he nth node in the linked list Node is defined as
/* Link list node
struct node
{
int data;
struct node* next;
node(int x){
data = x;
next = NULL;
}
};
*/
// Should return data of node at given index. The function may
// assume that there are at least index+1 nodes in linked list
int GetNth(struct node* head, int index){
// Code here
node* q;
int current_index=1;
for (q=head;q!=NULL;q=q->next)
{
if (current_index==index)
{
return q->data;
}
current_index++;
}
}