-
Notifications
You must be signed in to change notification settings - Fork 50
/
Kth element in Linked List from End.cpp
155 lines (100 loc) · 2.12 KB
/
Kth element in Linked List 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/*
Q) Given a linked list with n nodes. Find the kth element from
last without computing the length of the linked list.
Input Format
First line contains space separated integers representing the node
values of the linked list. The list ends when the input comes as '-1'.
The next line contains a single integer k.
Constraints
n < 10^5
Output Format
Output a single line containing the node value at the kth element from last.
Sample Input
1 2 3 4 5 6 -1
3
Sample Output
4
Explanation
The linked list is 1 2 3 4 5 6. -1 is not included in the list.
So the third element from the last is 4
Kth element from end is n-k from start
toh vohi use kiya hai using fast and slow pointer
also, creation of linked list, till data!= -1
*/
#include<iostream>
using namespace std;
class node
{
public:
int data;
node * next;
node(int d)
{
data = d;
next = NULL;
}
};
void insertAtTail(node *&head,int data)
{
if(head==NULL)
{
head=new node(data);
return;
}
node *t=head;
while(t->next!=NULL)
{
t=t->next;
}
t->next=new node(data);
return;
}
node* take_input(node*&head)
{
int data;
cin >> data;
// pass by reference toh no need
//node* head = NULL;
while(data!= -1)
{
insertAtTail(head, data);
cin >> data;
}
return head;
}
void print (node* temp)
{
while(temp!=NULL)
{
cout << temp -> data << " --> ";
temp = temp -> next;
}
cout << "NULL" << endl;
}
node* KthNodefromEnd(node* head, int k)
{
node* fast = head;
node* slow = head;
for(int i = 0; i < k; i++)
{
// traversal of N nodes
fast = fast -> next;
}
while(fast!=NULL)
{
// N-K from begin and K at end is same
fast = fast -> next;
slow = slow -> next;
}
return slow;
}
int main()
{
node *head=NULL;
take_input(head);
int position;
cin >> position;
node* answer = KthNodefromEnd(head,position);
cout << answer -> data;
return 0;
}