题目大意
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
Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤10^5) 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.
思路
- 抽象的链表
- 单链表的逆转
#include<stdio.h>
#include<stdlib.h>
struct List{
int data;
int nextp;
};
int reverse(struct List tmp[],int firstplace,int K,int N)
{
int newp,oldp,tmpp;
newp=firstplace;
oldp=tmp[firstplace].nextp;
int cnt=1;
int _first,_new,_old,_tmp;
int head,rear;
for(int i=0;i<K-1;i++){
tmpp=tmp[oldp].nextp; /*保留old所在位置*/
tmp[oldp].nextp=newp; /*old指针反向*/
newp=oldp;
oldp=tmpp;
}
rear=firstplace;/*reverse后新尾巴*/
head=newp; /*将表头与new相连*/
~~判断有几组需要做反向操作~~
int t=N-cnt*K;
if(t<K)
tmp[rear].nextp=oldp;/*,只有一组,将不用reverse的剩余链连入,如上图中的1和5*/
else{
for(int j=0;j<N/K-1;j++) { /*进行N/K次reverse*/
_first=oldp;
newp=_first;
oldp=tmp[newp].nextp;
for(int i=0;i<K-1;i++){ /*重复reverse操作,可将上述代码写成函数重复使用*/
tmpp=tmp[oldp].nextp;
tmp[oldp].nextp=newp;
newp=oldp;
oldp=tmpp;
}
tmp[rear].nextp=newp; /新reverse链连入上一个链*/
rear=_first;/*更新rear*/
}
if(N%K==0)
tmp[rear].nextp=-1;
else if(N%K>0)
tmp[rear].nextp=oldp;/*不用做reverse操作的链直接连入*/
}
return head;
}
int main()
{
int firstplace,N,K;
int p,data,next;
scanf("%d%d%d",&firstplace,&N,&K);
struct List l[100005]; /*模拟地址存储*/
for(int i=0;i<N;i++) {
scanf("%d%d%d",&p,&data,&next);
l[p].data=data;
l[p].nextp=next;
}
int num=1;int real_next;
real_next=firstplace;
while(l[real_next].nextp!=-1){
num++;
real_next=l[real_next].nextp;
}
int _p,_data,_next;
_p=reverse(l,firstplace,K,num);
for(int i=0;i<num;i++) {
_data=l[_p].data;
_next=l[_p].nextp;
if(_next!=-1)
printf("%05d %d %05d\n",_p,_data,_next);
else
printf("%05d %d -1\n",_p,_data);
_p=_next; }
return 0;
}