forked from skylarbpayne/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkthToLast.cpp
More file actions
47 lines (40 loc) · 791 Bytes
/
kthToLast.cpp
File metadata and controls
47 lines (40 loc) · 791 Bytes
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
/**
* Author: Skylar Payne
* Date: October 28, 2014
* Implement an algorithm to find the kth to last element of a singly linked list.
**/
#include <iostream>
class Node
{
public:
Node* next;
int data;
Node(int d, Node* n = nullptr) : next(n), data(d) { }
};
Node* kthToLast(unsigned int k, Node* list)
{
Node* end = list;
for(unsigned int i = 0; i < k && end->next != nullptr; ++i)
{
end = end->next;
}
Node* kthFromLast = list;
while(end->next != nullptr)
{
kthFromLast = kthFromLast->next;
end = end->next;
}
return kthFromLast;
}
int main(int argc, char** argv)
{
Node* list = nullptr;
for(unsigned int i = 0; i < 10; ++i)
{
list = new Node(i, list);
}
for(unsigned int i = 0; i < 10; ++i)
{
std::cout << kthToLast(i, list)->data << std::endl;
}
}