-
Notifications
You must be signed in to change notification settings - Fork 216
/
Copy pathlinked_list_kth_node_from_end.cpp
65 lines (65 loc) · 1.33 KB
/
linked_list_kth_node_from_end.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
// Finding Kth node from end of a LinkedList
// Program Author : Abhisek Kumar Gupta
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int d){
data = d;
next = NULL;
}
};
void insert_at_tail(node *&head, int data){
if(head == NULL){
head = new node(data);
return;
}
node *n = new node(data);
node * temp = head;
while(temp -> next != NULL){
temp = temp->next;
}
temp->next = n;
}
void print_linked_list(node *head){
while(head != NULL){
cout << head->data << "->";
head = head->next;
}
}
void makeLinkedList(node *&head){
int data;
cin >> data;
while(data != -1){
insert_at_tail(head, data);
cin >> data;
}
}
node* kth_node_from_end(node *head, int k){
if(head->next == NULL || head == NULL){
return head;
}
node *slow = head;
node *fast = head;
while(k--){
fast = fast->next;
}
while(fast){
fast = fast->next;
slow = slow->next;
}
return slow;
}
int main(){
node *head = NULL;
makeLinkedList(head);
print_linked_list(head);
int k;
cin >> k;
node *kth_node = kth_node_from_end(head, k);
cout << endl;
cout << kth_node->data << endl;
return 0;
}