02-線性結構3 Reversing Linked List (25分)

永不放棄的Tom發表於2020-11-22
	                      Reversing Linked List

在這裡插入圖片描述

#include<stdio.h>
#define Maxsize 100002
typedef struct node{
    int data;
    int next;
}Node;
int readin(Node arry[]);
int Reversing(Node arry[],int head, int cnt);
int Count(Node arry[],int head);
void Print(Node arry[],int head);
int N,K;
int main(void)
{
    Node arry[Maxsize];
    int head,fhead;
    head = readin(arry);
    fhead = head;
    int cnt = Count(arry,head);
    head = Reversing(arry,fhead,cnt);
    Print(arry, head);
    getchar();getchar();
    return 0;
}

int readin (Node arry[])
{
    int firsthead,add,data,next;
    scanf("%d %d %d",&firsthead, &N, &K);
    for(int i=0; i<N ; i++){
        scanf("%d %d %d",&add, &data, &next);
        arry[add].data = data;
        arry[add].next = next;
    }
    return firsthead;  //將頭節點傳出去!
}
int Count(Node arry[],int firhead)
{
    
     int count=0,head = firhead;
     while(head != -1 ){
         count++;
         head = arry[head].next;
     }
     return count;
}
int Reversing(Node arry[],int head, int cnt)
{
    // 存在多少個節點 
    int n = cnt / K;   // 存在多少個K區間
    int i,j,flag,phead,tail1,tail2,p1,p2,p3;
    p1 =phead = head; flag = 0; tail1=head; //避免迴圈設定new = head  同時需要儲存第一個節點 
    p2 = arry[p1].next;p3 = arry[p2].next;
    if(K==1) return p1; // K==1 表示節點不用操作
    for(i=0 ; i<n ;i++){
        for(j=0 ;j<K-1 ;j++ ){
            if(j==0 && flag==0){
                tail1 = p1; 
            }else if(j==0 && flag>0){
                tail2 = p1;
            }
            arry[p2].next = p1; p1 = p2 ; p2 = p3; p3 = arry[p3].next;
            if(j==K-2 && flag==0){
                phead = p1; flag++ ;p1 = p2; p2 = p3; p3 = arry[p3].next;
            }else if(j==K-2 && flag>0){
                arry[tail1].next = p1; tail1 = tail2; p1 = p2 ; p2 = p3; p3 = arry[p3].next;
            }
        }      
    }
    arry[tail1].next = p1;
    return phead; //將處理好的頭節點返回出去
}

void Print(Node arry[],int head){
  int phead = head;
    while(arry[phead].next != -1){
        printf("%05d %d %05d\n",phead, arry[phead].data, arry[phead].next );
        phead = arry[phead].next;
    }
    printf("%05d %d -1\n",phead, arry[phead].data, arry[phead].next);
}

今晚還趕作業,後面幾天在詳細寫細節

相關文章