鏈表的逆置(頭插法)

#include<stdio.h>

#include<stdlib.h>

#define N 5

typedef struct node{

   int  data;

   struct node * next;

}ElemSN;

ElemSN  * Createlink(int a[],int n){  

    int i;

    ElemSN * h=NULL, * p;

    for( i=N-1;i>=0;i--) {

          p=(ElemSN *)malloc(sizeof(ElemSN));

      p->data=a[i];

      p->next=h;

      h=p;

    }

    return h;

  }

   void printlink(ElemSN * h){

       ElemSN * p;

       for(p=h;p;p=p->next)

           printf("%d\n",p->data);

   }

  ElemSN * Prelink(ElemSN * h) {

       ElemSN * h1=NULL, * p;     //h1鏈表的頭結點

       while(h){                    //h爲空截止,表示鏈表已經逆置

            p=h;                    //頭結點給p

            h=h->next;        //頭結點後移

            p->next=h1;      //頭插

            h1=p;                //設置頭指針

       }   

      return h1;

}

int main(void){

        int a[N]={10,20,30,40,50};

        ElemSN * head;

        head=Createlink(a,9);

        head=Prelink(head);

        printlink(head);

        return 0;

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章