7-19 求链式线性表的倒数第K项 (20分)

不知道题目说的尽可能高效的算法是啥,我就只按我会的来了,无语……

这代码能不能AC就看运气,有时候最后两个测试点会超时,再提交一次又能AC了。

。 1 #include <iostream>
 2 #include <string>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 struct node
 7 {
 8     int data;
 9     struct node* next;
10 };
11 
12 typedef struct node* node_ptr;
13 int null_flag = 0;
14 
15 int main()
16 {
17     int K;
18         cin >> K;
19         node_ptr p_end = NULL;
20         int temp;
21         while(1)
22         {
23             cin >> temp;
24             if (temp < 0)
25             {
26                 break;
27             }
28             else
29             {
30                 node_ptr s = new struct node;
31                 s->data = temp;
32                 s->next = p_end;
33                 p_end = s;
34             }
35         }
36         int t = 1;
37         node_ptr ptemp = p_end;
38         while (t++ < K)
39         {
40             if (NULL != ptemp->next)
41             {
42                 ptemp = ptemp->next;
43                 continue;
44             }
45             else
46             {
47                 break;
48             }
49         }
50         if (t == K + 1)
51             cout << ptemp->data << endl;
52         else
53             cout << "NULL";
54     return 0;
55 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值