-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.2(KthToLast).cpp
More file actions
95 lines (80 loc) · 1.33 KB
/
2.2(KthToLast).cpp
File metadata and controls
95 lines (80 loc) · 1.33 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <iostream>
#include <vector>
using namespace std;
class linkedlist{
public:
struct Node{
int data;
Node *next;
};
linkedlist (){
head = NULL;
}
void insert(int data){
Node *n = new Node();
n->data =data;
n->next = head;
head = n;
}
void display(){
Node *temp = new Node();
temp = head;
while(temp->next != NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<temp->data;
}
int kthElement(int k){
Node *temp = new Node();
temp = head;
vector<int> count;
while(temp->next!= NULL){
count.push_back(temp->data);
temp=temp->next;
}
count.push_back(temp->data);
return count[count.size() - (count.size()-k)-1];
}
void printK(int K){
if(head==NULL){
cout<<"empty";
}
Node* first;
Node* second;
first = head;
second = head;
int count =0;
int count2 =0;
while(first->next!=NULL){
count++;
if(count>=K){
second=second->next;
count2++;
}
first= first->next;
//second=second->next;
}
second = head;
for(int i=0; i<count-count2; i++){
second=second->next;
}
cout<<second->data;
}
private:
Node *head;
};
int main(){
linkedlist list;
int k=3;
int n=0;
list.insert(5);
list.insert(10);
list.insert(5);
list.insert(8);
list.insert(9);
n= list.kthElement(k);
cout<<n;
cout<<endl;
list.printK(k);
}