02 - 线性结构 2 Reversing Linked List (25 分)


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


#include 

define MAX 100000

typedef struct{
int data;
int next;
}Node;
//计算并返回数组中在链表中的结点
int CountNodes(Node*list, int pList) {
int cnt = 1;
while((pList = list[pList].next) != -1) cnt++;
return cnt;
}
//list指向数组 plist为第一个元素的地址 n为总数 k为反转单位
int ReverseK(Node*list, int pList, int n, int k) {
//前一节点,当前节点,下一节点的地址
int prevNode, currNode, nextNode;
prevNode = -1;
currNode = pList;
nextNode = list[currNode].next;
int lastHead, head = -1;
int i ,j;
for( i = 0; i < n / k; i++){
lastHead = head;//记录前一段的(未逆转的)头结点,以便连接到当前段的(未逆转的)尾节点
head = currNode;//记录当前段的头结点
for(j = 0; j < k; j++) { //k个结点逆转,后一节点指向前一节点
list[currNode].next = prevNode;
prevNode = currNode;
currNode = nextNode;
nextNode = list[nextNode].next;
}
if(i == 0)//第一段逆转后的头结点当作表头返回
pList = prevNode;
else
list[lastHead].next = prevNode;//连接逆转后的前后两段
}
list[head].next = currNode; //不用逆转的剩余部分加上
return pList;
}
void printList(Node* list, int p) {
while(list[p].next != -1){
printf("%05d %d %05d\n", p, list[p].data, list[p].next);
p = list[p].next;
}
printf("%05d %d %d\n", p, list[p].data, list[p].next);
}
int main() {
int pList, n, k;
scanf("%d%d%d", &pList, &n, &k);
Node list[MAX];
int addr, data, next,i;
for(i = 0; i < n; i++){
scanf("%d%d%d", &addr, &data, &next);
list[addr].data = data;
list[addr].next = next;
}
int num = CountNodes(list, pList);
int pNewList = ReverseK(list, pList, num, k);
printList(list, pNewList);
return 0;
}

你可能感兴趣的:(02 - 线性结构 2 Reversing Linked List (25 分))