PAT甲级1074 Reversing Linked List (25分)

Dear 丶 2023-07-22 05:59 75阅读 0赞

题目截图
输入输出【程序思路】
先根据地址按顺序读入节点,入栈,当栈里的元素个数等于k时全部出栈,并按出栈顺序保存,最后若栈不为空,则全部出栈并按出栈的稀饭顺序保存,最后输出各节点
注意:输入的节点中有可能存在无用节点需要过滤,这里我使用map映射来实现过滤
【代码实现】

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct node{
  4. int addrest,data,next;
  5. }t;
  6. int stk[100005];
  7. int main(){
  8. map<int,node> a;
  9. vector<int> c;
  10. int head,n,i,k,top = -1;
  11. cin>>head>>n>>k;
  12. for(i=0;i<n;i++) {
  13. cin>>t.addrest>>t.data>>t.next;
  14. a[t.addrest] = t;
  15. }
  16. while(head!=-1) {
  17. stk[++top] = head;
  18. if(top + 1 == k)
  19. while(top != -1)
  20. c.push_back(stk[top--]);
  21. head = a[head].next;
  22. }
  23. for(i = 0; i <= top; i++)
  24. c.push_back(stk[i]);
  25. for (i = 0; i < c.size() - 1; i++)
  26. printf("%05d %d %05d\n",c[i],a[c[i]].data,c[i+1]);
  27. printf("%05d %d -1\n",c[i],a[c[i]].data);
  28. return 0;
  29. }

发表评论

表情:
评论列表 (有 0 条评论,75人围观)

还没有评论,来说两句吧...

相关阅读