-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path15_KthNodeFromEnd.cpp
63 lines (54 loc) · 916 Bytes
/
15_KthNodeFromEnd.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
#include <iostream>
using namespace std;
struct ListNode{
int value;
ListNode *next;
};
ListNode* FindKthToTail(ListNode *pHead, int k)
{
if (pHead == NULL || k <= 0)
return NULL;
ListNode *pAhead = pHead;
ListNode *pBehind = pHead;
for (int i=0; i < k-1; i++)
{
if(pAhead->next != NULL)
pAhead = pAhead->next;
else
return NULL;
}
while(pAhead->next != NULL)
{
pAhead = pAhead->next;
pBehind = pBehind->next;
}
return pBehind;
}
int main()
{
int n, k, tmp;
while (cin >> n >> k)
{
if (n <= 0)
{
cout << "NULL" << endl;
continue;
}
ListNode *root = new ListNode;
cin >> tmp;
root->value = tmp;
root->next = NULL;
ListNode *index = root;
while (--n)
{
index->next = new ListNode;
index = index->next;
cin >> tmp;
index->value = tmp;
index->next = NULL;
}
index = root;
cout<<FindKthToTail(root, k)->value<<endl;
}
return 0;
}