Reversing Linked List
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.
out 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.
在这里插入代码片
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 100000
typedef int ElementType;
typedef struct LNode *lnode;
struct LNode{
ElementType addr; //地址
ElementType data; //数据
ElementType nextaddr; //下一个地址
lnode Next;
};
typedef lnode List;
void Initlist(struct LNode *a,ElementType *data,ElementType *next,ElementType n);
void Reverselist(List head,ElementType k,ElementType n);
void printlist(List head);
int main(){
ElementType firstaddr,n,k,temp;
ElementType data[MAX_SIZE]; //保存数据,索引号代表地址
ElementType next[MAX_SIZE]; //保存下一个地址,索引号代表地址
scanf("%d %d %d",&firstaddr,&n,&k);
struct LNode a[n+1];
a[0].nextaddr = firstaddr;
for(int i = 0;i<n;i++){
scanf("%d",&temp);
scanf("%d %d",&data[temp],&next[temp]);
}
Initlist(a,data,next,n);
Reverselist(a,k,n);
printlist(a);
return 0;
}
//初始化链表
void Initlist(struct LNode *a,ElementType *data,ElementType *next,ElementType n){
for(int i = 1;i<n+2;i++){
if(a[i-1].nextaddr == -1){
a[i-1].Next = NULL;
break;
}
else{
a[i].addr = a[i-1].nextaddr;
a[i].data = data[a[i].addr];
a[i].nextaddr = next[a[i].addr];
a[i-1].Next = a+i;
}
}
}
//反转链表
void Reverselist(List head,ElementType k,ElementType n){
List HEAD,old,temp,p;
for(int i = 0;i<n/k;i++){
HEAD = head->Next;
old = HEAD->Next;
temp = NULL;
for(int j = 1;j<k;j++){
temp = old->Next;
old->Next = HEAD;
old->nextaddr = HEAD->addr;
HEAD = old;
old = temp;
}
head->Next->Next = old;
if(old!=NULL){
head->Next->nextaddr = old->addr;
}
else{
head->Next->nextaddr = -1;
}
p = head->Next; //保存head->next,用来改变head的值
head->Next = HEAD;
head->nextaddr = HEAD->addr;
head = p;
}
}
void printlist(List head){
List temp = head->Next;
while(temp){
if(temp->Next==NULL){
printf("%05d %d %d\n",temp->addr,temp->data,temp->nextaddr);
temp = temp->Next;
}
else{
printf("%05d %d %05d\n",temp->addr,temp->data,temp->nextaddr);
temp = temp->Next;
}
}
}