-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathnthNodeInLinkedList.cpp
More file actions
76 lines (60 loc) · 1.13 KB
/
nthNodeInLinkedList.cpp
File metadata and controls
76 lines (60 loc) · 1.13 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <bits/stdc++.h>
using namespace std;
// Link list node
class Node {
public:
int data;
Node* next;
};
void push(Node** head_ref, int new_data)
{
// allocate node
Node* new_node = new Node();
// put in the data
new_node->data = new_data;
// link the old list
// off the new node
new_node->next = (*head_ref);
// move the head to point
// to the new node
(*head_ref) = new_node;
}
// Takes head pointer of
// the linked list and index
// as arguments and return
// data at index
int GetNth(Node* head, int index)
{
Node* current = head;
// the index of the
// node we're currently
// looking at
int count = 0;
while (current != NULL) {
if (count == index)
return (current->data);
count++;
current = current->next;
}
assert(0);
}
// Driver Code
int main()
{
// Start with the
// empty list
Node* head = NULL;
// Use push() to construct
// below list
// 1->12->1->4->1
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
// Check the count
// function
cout << "Element at index 3 is " << GetNth(head, 3);
return 0;
}
// This code is contributed by rathbhupendra