链表的逆置(头插法)
更新:HHH   时间:2023-1-7


#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 * h2=NULL, * p;     //h2链表的头结点

       while(h){                    //h为空截止,表示链表已经逆置

            p=h;                    //头结点给p

            h=h->next;        //头结点后移

            p->next=h2;      //头插

            h2=p;                //设置头指针

       }   

      return h2;

}

int main(void){

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

        ElemSN * head;

        head=Createlink(a,9);

        head=Prelink(head);

        printlink(head);

        return 0;

}



返回编程语言教程...