Skip to content

Commit c7a4952

Browse files
authored
Kth Element from The Last
1 parent 998198a commit c7a4952

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/* Hacker Blocks */
2+
/* Title - Kth Element from The Last */
3+
/* Created By - Akash Modak */
4+
/* Date - 2/8/2020 */
5+
6+
// Given a linked list with n nodes. Find the kth element from last without computing the length of the linked list.
7+
8+
// Input Format
9+
// 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.
10+
11+
// Constraints
12+
// n < 10^5
13+
14+
// Output Format
15+
// Output a single line containing the node value at the kth element from last.
16+
17+
// Sample Input
18+
// 1 2 3 4 5 6 -1
19+
// 3
20+
// Sample Output
21+
// 4
22+
// Explanation
23+
// 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
24+
25+
#include<iostream>
26+
using namespace std;
27+
class Node{
28+
public:
29+
int data;
30+
Node* next;
31+
Node(int d){
32+
this->data=d;
33+
this->next=NULL;
34+
}
35+
};
36+
void buildlist(Node* &head,int data){
37+
if(head==NULL){
38+
Node *temp = new Node(data);
39+
head = temp;
40+
return;
41+
}
42+
Node *c = head;
43+
while(c->next!=NULL)
44+
c=c->next;
45+
Node * temp= new Node(data);
46+
c->next = temp;
47+
return;
48+
}
49+
50+
int main() {
51+
Node *head = NULL;
52+
int temp1;
53+
cin>>temp1;
54+
while(temp1!=-1){
55+
buildlist(head,temp1);
56+
cin>> temp1;
57+
}
58+
int k;
59+
cin>>k;
60+
Node * temp;
61+
temp=head;
62+
while(k--){
63+
temp=temp->next;
64+
}
65+
Node * slow = head;
66+
while(temp!=NULL)
67+
{
68+
temp=temp->next;
69+
slow=slow->next;
70+
}
71+
cout<<slow->data<<endl;
72+
return 0;
73+
}

0 commit comments

Comments
 (0)