1 #include <iostream> 2 #include <string> 3 #include <cmath> 4 #include <vector> 5 using namespace std; 6 7 8 9 struct ListNode{ 10 int val; 11 ListNode* next; 12 }; 13 14 int main() 15 { 16 17 int node_num; 18 while(cin>>node_num){ 19 ListNode * temp,*query; 20 if(node_num == 0) //如果输入数量为0,直接跳过该轮循环 21 continue; 22 23 //单独处理头结点 24 int head_node_val; 25 cin>>head_node_val; 26 ListNode *head = new ListNode; 27 head->val = head_node_val; 28 head->next = nullptr; 29 query = head; 30 //继续构造链表 31 for(int i= 0; i<node_num-1;i++){ 32 int input; 33 cin>>input; 34 temp = new ListNode; 35 temp->val = input; 36 temp->next = nullptr; 37 38 query->next = temp; 39 query = temp; 40 41 } 42 43 44 //倒数第k个结点(1为基),所以是正向遍历的第node_num-k+1个结点(1为基) 45 int k; 46 cin>> k; 47 if(k==0){ //非法输入 48 cout<<"0"<<endl; 49 continue; 50 } 51 52 if(node_num<k) //k太大了 53 { 54 cout<<"NULL"<<endl; 55 continue; 56 } 57 58 query = head; //遍历用的指针,初始值为头结点 59 if(node_num-k == 0){ //如果正好是第一个结点,直接返回 60 cout<<head->val<<endl; 61 continue; 62 } 63 64 65 for(int i=1; i<(node_num-k+1);i++){ 66 query = query->next; 67 } 68 cout<<query->val<<endl; 69 } 70 return 0; 71 }