Given a singly linked list L. Let us consider every K nodes as a block (if there are less than K nodes at the end of the list, the rest of the nodes are still considered as a block). Your job is to reverse all the blocks in L. For example, given L as 1→2→3→4→5→6→7→8 and K as 3, your output must be 7→8→4→5→6→1→2→3.node
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 size of a block. The address of a node is a 5-digit nonnegative integer, and NULL is represented by −1.ios
Then N lines follow, each describes a node in the format:git
Address Data Next
where Address
is the position of the node, Data
is an integer, and Next
is the position of the next node.算法
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.less
00100 8 3 71120 7 88666 00000 4 99999 00100 1 12309 68237 6 71120 33218 3 00000 99999 5 68237 88666 8 -1 12309 2 33218`
71120 7 88666 88666 8 00000 00000 4 99999 99999 5 68237 68237 6 00100 00100 1 12309 12309 2 33218 33218 3 -1
现给定一个链表L,假定每K个位一块,最后不足K个的也为一块,如今要求将全部的块进行逆置,块内保证有序。ide
PAT的静态链表的题目,要把握其中的一个特色就是,结点的地址和数值是绑定的,next彻底不须要操心,最后将全部结点放在一片内存连续的区域天然就能够获得了。咱们这里采用排序的方法来解决这个问题,给每个结点赋值一个flag表明每个结点的块号 ,id表明每个结点初始的相对顺序,那么排序规则就是先根据flag大的进行排序,flag相同的直接按照id进行排序便可。接下来就是flag和id的获取,对于id来讲,链表的起点为0,日后依次累加,而flag为其id/K,拍完序以后,直接输出便可,只须要注意next的输出,在最后一个结点得输出-1,不然输出下一个结点的地址就行。spa
#include<cstdio> #include<string> #include<iostream> #include<vector> #include<algorithm> using namespace std; struct Node{ int address; int data; int next; int flag;// 每个结点的块号 int id;// 每个结点初始的相对顺序 }nodes[100005]; vector<Node> list; bool cmp(const Node &a,const Node &b){ return a.flag!=b.flag?a.flag>b.flag:a.id<b.id; } int main(){ int begin,N,K; scanf("%d %d %d",&begin,&N,&K); Node node; for (int i = 0; i < N; ++i) { scanf("%d %d %d",&node.address,&node.data,&node.next); nodes[node.address] = node; } int num = 0; while(begin!=-1){ nodes[begin].id = num; nodes[begin].flag = num/K; ++num; list.push_back(nodes[begin]); begin = nodes[begin].next; } sort(list.begin(),list.end(),cmp); for(int i=0;i<list.size();++i){ printf("%05d %d ",list[i].address,list[i].data); if(i<list.size()-1){ printf("%05d\n",list[i+1].address); } else { printf("-1"); } } return 0; }