-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkth_element.cpp
125 lines (114 loc) · 1.92 KB
/
kth_element.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
#include <iostream>
using namespace std;
class Node{
public:
Node(){
next = NULL;
}
//void setValue(int value){
// data = value;
//}
//int getValue(){
// return data;
//}
int data;
Node* next;
};
class LinkedList{
public:
LinkedList(){
head = NULL;
}
void printAll();
void inserToFront(int);
void insertToBack(int);
int kthElement(int);
private:
Node* head;
};
void LinkedList::printAll(){
Node* p;
p = head;
while(p != NULL){
cout << p->data << endl;
p = p->next;
}
}
void LinkedList::insertToBack(int value){
Node* node = new Node;
node->data = value;
if(head == NULL){
node->next = NULL;
}
else{
node->next = head;
}
head = node;
}
void LinkedList::inserToFront(int value){
Node* node = new Node;
if(head == NULL){
head = node;
}
else{
Node* iter = head;
while(iter->next != NULL){
iter = iter->next;
}
iter->next = node;
}
node->data = value;
node->next = NULL;
}
int LinkedList::kthElement(int counter){
Node* node = new Node;
node = head;
Node* prev_node = new Node;
prev_node = head;
int i=0;
/*while(node->next != NULL){
if(i==(counter-1)){
break;
}
node = node->next;
i= i+1;
}
if(i != (counter-1)){
cout << "not enough elements in list"<<endl;
return -1;
}
*/
for(int i=0; i<counter-1; i++){
if(node->next != NULL){
node = node->next;
}
else{
cout<< "not enough elements in the list"<<endl;
return -1;
}
}
while(node->next != NULL){
node = node->next;
prev_node = prev_node->next;
}
return prev_node->data;
}
int main(){
LinkedList list;
list.insertToBack(1);
list.insertToBack(2);
list.inserToFront(3);
list.inserToFront(3);
list.inserToFront(4);
//list.inserToFront(5);
//list.inserToFront(6);
//list.inserToFront(4);
//list.inserToFront(3);
//list.inserToFront(9);
//list.inserToFront(15);
list.printAll();
cout<< endl;
cout<< "return the 5th to last element: ";
cout<< list.kthElement(5) << endl;
return 0;
}