forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nthToLastNode.cpp
69 lines (56 loc) · 1.18 KB
/
nthToLastNode.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
/*
* Find nth to last node in a linked list.
*
*/
#include<iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int v): val{v}, next{nullptr} { }
};
ListNode* nthToLastNode( ListNode *head, int n )
{
ListNode *ptr1 = head;
ListNode *ptr2 = head;
int i = 1;
while ( ptr1 && i <= n) {
ptr1 = ptr1->next;
++i;
}
while( ptr1) {
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
return ptr2;
}
void insert( ListNode* & head, int v )
{
ListNode *newNode = new ListNode(v);
if ( head == nullptr) {
head = newNode;
} else {
ListNode *temp = head;
while( temp->next != nullptr ) {
temp = temp->next;
}
temp->next = newNode;
}
}
void iterateList(ListNode *head) {
while(head) {
std::cout << head->val << "-->";
head = head->next;
}
std::cout << "NULL" << std::endl;
}
int main()
{
ListNode * head = nullptr;
insert(head, 3);
insert(head, 2);
insert(head, 1);
insert(head, 5);
iterateList(head);
ListNode *nthNodeToLastNode = nthToLastNode(head, 2);
std::cout << nthNodeToLastNode->val << std::endl;
}