注意;技巧题,也就是双指针问题。
描述
利用单链表表示一个整数序列,请实现一个时间复杂度为O(n)、空间复杂度为O(1)的算法,通过一趟遍历在单链表中确定倒数第k个结点。
输入
多组数据,每组数据有三行,第一行为链表的长度n,第二行为链表的n个元素(元素之间用空格分隔),第三行为k。当n=0时输入结束。
输出
对于每组数据分别输出一行,输出每个链表的倒数第k个结点对应的数值。
样例输入1 复制
7
5 2 3 4 50 100 70
3
5
20 30 10 4 5
5
0
样例输出1
50
201
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#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#define OK 1
using namespace std;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;
LNode *first;
LNode *second;
bool InintList(LinkList &L)
{
L=new LNode;
L->next=NULL;
return OK;
}
int main()
{
int num;
while(cin>>num&&num!=0)
{
LinkList L;
InintList(L);
L->next=new LNode;
LNode *p=L->next;
LNode *pre=L;
for(int i=1;i<=num;i++)
{
cin>>p->data;
p->next=new LNode;
p=p->next;
pre=pre->next;
}
pre->next=NULL;
int position;
cin>>position;
first=L->next;
second=L->next;
for(int i=1;i<=position;i++)
{
first=first->next;
}
while(first)
{
first=first->next;
second=second->next;
}
cout<<second->data<<endl;
}
return 0;
}