1074. Reversing Linked List (25)

╰+攻爆jí腚メ 2022-05-30 02:58 251阅读 0赞

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K = 3, then you must output 3→2→1→6→5→4; if K = 4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (<= 105) which is the total number of nodes, and a positive K (<=N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

  1. 00100 6 4
  2. 00000 4 99999
  3. 00100 1 12309
  4. 68237 6 -1
  5. 33218 3 00000
  6. 99999 5 68237
  7. 12309 2 33218

Sample Output:

  1. 00000 4 33218
  2. 33218 3 12309
  3. 12309 2 00100
  4. 00100 1 99999
  5. 99999 5 68237
  6. 68237 6 -1

题目大意:

代码:

  1. #include<stdio.h>
  2. #include<stack>
  3. #include<vector>
  4. using namespace std;
  5. struct node
  6. {
  7. int id;
  8. int data;
  9. int next;
  10. }List[100001];
  11. vector<struct node> v;
  12. int main()
  13. {
  14. int i,j,n,m,k,t,first,id,data,next,index,second,num=0;
  15. scanf("%d %d %d",&first,&n,&k);
  16. for(i=0;i<n;i++)
  17. {
  18. scanf("%d %d %d",&id,&data,&next);
  19. List[id].id=id;
  20. List[id].data=data;
  21. List[id].next=next;
  22. }
  23. stack<struct node> s;
  24. t=0;
  25. //printf("\n");
  26. second=first;
  27. while(second!=-1)
  28. {
  29. second=List[second].next;
  30. num++;
  31. }
  32. while(first!=-1)
  33. {
  34. if(num%k!=0&&(num-t<=num%k))
  35. {
  36. v.push_back(List[first]);
  37. }
  38. else
  39. {
  40. s.push(List[first]);
  41. t++;
  42. if(t%k==0)
  43. {
  44. while(!s.empty())
  45. {
  46. struct node tmp=s.top();
  47. s.pop();
  48. v.push_back(tmp);
  49. }
  50. }
  51. }
  52. first=List[first].next;
  53. }
  54. for(i=0;i<v.size();i++)
  55. {
  56. if(i==v.size()-1)
  57. {
  58. printf("%05d %d -1\n",v[i].id,v[i].data);
  59. }
  60. else
  61. {
  62. printf("%05d %d %05d\n",v[i].id,v[i].data,v[i+1].id);
  63. }
  64. }
  65. return 0;
  66. }

发表评论

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

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

相关阅读