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 (≤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.
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:
00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
Sample Output:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1
思路:
1.排序:把链表信息存入结构体数组,找到开始节点,以flag记载其下标,以选择排序,将链表以链接顺序依次排序
2.逆转:每K个为一组,组内进行元素逆转,暂时不动链表地址;将所有组都逆转完毕后,由于逆转后链表的节点地址(addr)并不会改变,所以从头开始,改变所有的指向下一个链表的指针(next_addr),使其成链即可。
3.依次输出
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#define NUM 100000
using namespace std;
typedef struct Node{
char addr[6];
int data;
char next_addr[6];
};
Node list[NUM];
void swap(Node list[], int a, int b){//交换list数组中下标为a,b的两个元素
if(a==-1)
return;
Node tmp = list[a];
list[a] = list[b];
list[b] = tmp;
}
int search(Node list[], int s, int N, char* addr){
//寻找地址为addr的节点的下标
for(int i = s; i < N; i++){
if(!strcmp(list[i].addr, addr))
return i;
}
if(!strcmp(addr,"-1"))
return -2;
return -1;//如果找不到这个点的下一个节点
}
int main(){
char start_addr[6];
int N, K;
int flag; //头节点的下标
scanf("%s %d %d",start_addr,&N,&K);
int num = N;//链表中元素个数
for(int i = 0; i < N; i++){
scanf("%s%d%s",list[i].addr, &list[i].data, list[i].next_addr);
if(!strcmp(list[i].addr, start_addr))
flag = i;
}
for(int i = 0; i < N; i++){
swap(list,flag,i);
flag = search(list, i+1, num, list[i].next_addr);
if(flag == -2){
num = i + 1;
break;
}
}
//已经排序完成,下面进行逆转
int s = 0;
for(int i = 0; i < num/K ; i++){
for(int j = s; j < s + K/2; j++){
swap(list, j, (2*i+1)*K-j-1);
}
s += K;
}
for(int i = 0; i < num-1; i++){
strcpy(list[i].next_addr, list[i+1].addr);
}
strcpy(list[num-1].next_addr, "-1");
for(int i = 0; i < num; i++)
printf("%s %d %s\n",list[i].addr,list[i].data,list[i].next_addr);
return 0;
}