Last active
March 29, 2019 07:15
-
-
Save nyufeng/e5da4fe28a53084350076dd50c84b3d2 to your computer and use it in GitHub Desktop.
02-线性结构3 Reversing Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#define MAXNUM 100000 | |
struct LinkedNode{ | |
int num; | |
int next; | |
}; | |
typedef struct LinkedNode *linked, node; | |
void printData(linked data[], int address); | |
int main(){ | |
linked data[MAXNUM]; | |
int firstAddress, N, K; | |
scanf("%d %d %d", &firstAddress, &N, &K); | |
int address, num, next; | |
for(int i = 0; i < N; i++){ | |
scanf("%d %d %d", &address, &num, &next); | |
data[address] = (linked)malloc(sizeof(node)); | |
data[address]->next = next; | |
data[address]->num = num; | |
} | |
if(K == 1){ | |
printData(data,firstAddress); | |
return 0; | |
} | |
int current = firstAddress, last = -1, count = 0, tmp, top = -1, bottom = firstAddress, nextBottom; | |
while(current != -1){ | |
tmp = data[current]->next; | |
data[current]->next = last; | |
last = current; | |
current = tmp; | |
count++; | |
if(count == K){ | |
if(top == -1){ | |
top = last; | |
}else{ | |
data[bottom]->next = last; | |
bottom = nextBottom; | |
} | |
nextBottom = current; | |
last = -1; | |
count = 0; | |
} | |
} | |
if(last != -1){ | |
data[bottom]->next = nextBottom; | |
int rev = -1; | |
while(last != -1){ | |
tmp =data[last]->next; | |
data[last]->next = rev; | |
rev = last; | |
last = tmp; | |
} | |
} | |
printData(data, top); | |
} | |
void printData(linked data[], int address){ | |
while(address != -1){ | |
if(data[address]->next == -1){ | |
printf("%05d %d %d", address, data[address]->num, data[address]->next); | |
}else{ | |
printf("%05d %d %05d\n", address, data[address]->num, data[address]->next); | |
} | |
address = data[address]->next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment