浙大PAT反轉鏈表:7-2 Reversing Linked List

7-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 <stdio.h>
#define NUM 100005
typedef struct Node{
    int data;
    int next;
}Node;

Node List[NUM];

int reverse(int head,int K){
	//實現:first指向第一個反轉鏈頭,last指向反轉鏈尾,RHead指向新鏈頭
    int first = head,last = head,RHead = head;
    int k = K;
    while(last!=-1&&k!=1){//last後移K-1位,指向鏈尾
        last = List[last].next;
        k--;
    }
    k = K;//更新K
    if(last!=-1)
        RHead = last;//更新新鏈頭
    
    //反轉鏈,反轉後first,last分別重新指向下一個反轉鏈頭尾
    while(last!=-1){
        int p = first;
        while(first!=last){
        	//把first(p)指向的結點插入到last的後面
            first = List[p].next;	//first右移
            List[p].next = List[last].next;	//p後繼改爲last後繼
            List[last].next = p;	//last後繼改爲p
            p = first;	//更新p到first
        }
		//更新first,last
        while(--k){//p右移K-1位到反轉鏈尾,用來接上下一個反轉鏈頭
            p = List[p].next;
        }
        k = K;//更新K
        first = List[p].next;
        last = List[p].next;
        while(last!=-1&&k!=1){//last右移K-1位,指向新的反轉鏈尾
            last = List[last].next;
            k--;
        }
        k = K;
        //將新的反轉鏈頭接到p的後面 
        if(last!=-1)//如果last==-1,不用把last接在p後面,並且結束while循環
        	List[p].next = last;
    }//一次循環結束:p指向更新後反轉鏈尾,first,last分別指向下一個反轉鏈頭尾
    return RHead;
}

int main(){
    int position,N,K;
    int p;
    scanf("%d %d %d",&position,&N,&K);
 
    for(;N>0;N--){
        scanf("%d",&p);
        scanf("%d %d",&(List[p].data),&(List[p].next));
    }
    int RHead = reverse(position,K);
    p = RHead;
 
    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",p,List[p].data,List[p].next);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章