HJ51~HJ60 华为机试题库
HJ51 输出单向链表中倒数第k个结点
题目:https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d?tpId=37&tqId=21274&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D2%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
本身是很简单的,就是限制条件有点多。这里用了队列来处理,一旦超出长度就出队,最后输出队头元素就ok。
1 #include<bits/stdc++.h> 2 using namespace std; 3 struct ListNode{ 4 int Key; 5 ListNode* Next; 6 ListNode(int x){ 7 Key=x; 8 Next=nullptr; 9 } 10 }; 11 ListNode* Add(ListNode* a,ListNode* b){ 12 a->Next=b; 13 return b; 14 } 15 void Work(ListNode* hd,int k){ 16 queue<ListNode*>que; 17 while(!que.empty())que.pop(); 18 while(1){ 19 que.push(hd); 20 if((int)que.size()>k)que.pop(); 21 if(hd->Next!=nullptr) hd=hd->Next; 22 else break; 23 } 24 cout<<que.front()->Key<<endl; 25 return; 26 } 27 void init(){ 28 int n,b; 29 ListNode* hd; 30 while(cin>>n){ 31 ListNode* a=new ListNode(0); 32 hd=a; 33 for(int i=1;i<=n;i++){ 34 cin>>b; 35 a=Add(a,new ListNode(b)); 36 } 37 cin>>n; 38 Work(hd->Next,n); 39 } 40 return; 41 } 42 int main(){ 43 ios_base::sync_with_stdio(false); 44 cin.tie(NULL); 45 init(); 46 return 0; 47 }