forked from Andrew9Tech/huawei_OJ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path输出单向链表中倒数第k个.cpp
48 lines (42 loc) · 867 Bytes
/
输出单向链表中倒数第k个.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
#include <iostream>
using namespace std;
typedef int ElemType;
struct ListNode
{
ListNode *next;
ElemType data;
};
int FindKthToTail(ListNode* pListHead, unsigned int k)
{
ListNode *pAhead = pListHead;
ListNode *pBehind = NULL;
for (unsigned int i = 0; i < k; i++)
{
pAhead = pAhead->next;
}
pBehind = pListHead;
while (pAhead->next != NULL)
{
pAhead = pAhead->next;
pBehind = pBehind->next;
}
return pBehind->data;
}
void main()
{
ListNode *pListNode, *PListNode, *qListNode;
int num, count = 0, k;
pListNode = PListNode = new ListNode;
cin >> num;
for (int i = 0; i<num; i++)
{
qListNode = new ListNode;
cin >> qListNode->data;
pListNode->next = qListNode;
pListNode = qListNode;
}
pListNode->next = NULL;
cin >> k; //输入要输出的位置
ListNode *head = PListNode->next;
cout << FindKthToTail(head, k) << endl;
}