7-19 求链式线性表的倒数第K项 (20分)
不知道题目说的尽可能高效的算法是啥,我就只按我会的来了,无语……
有时候最后两个测试点会超时,再提交一次又能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 }