1. 程式人生 > >C語言建立單向連結串列之正向建鏈

C語言建立單向連結串列之正向建鏈

建立單向連結串列之正向建鏈,首先定義一個結構體ElemSN,建立頭指標head,兩個中間變數p、q用於連線創建出的每一個節點的指標域。
#include"stdio.h"
#include"conio.h"
#include"malloc.h"
 
typedef struct ElemSN
{
       int data;
       struct ElemSN * next;
}ElemSN;
 
ElemSN * CreatLink(int  *a , int n);  //建立單向連結串列
void printLink(ElemSN * head);        //輸出單向連結串列
 
void printLink(ElemSN * head)
{
        for(; head ; head=head->next)
               printf("%d  ", head->data);
}
ElemSN * CreatLink(int  *a ,int n)
{
     int i;
     ElemSN *head=NULL;
     ElemSN *p, *q;
     for(i = 0 ; i < n ;i++)
     {
          p=(ElemSN *)malloc(sizeof(ElemSN));
          p->data=a[i];
          p->next=NULL;
          if(head==NULL)
                head = p;
          else                  
                q->next=p;
          q=p;
     }
     return  head;
}
void main(void)
{
      ElemSN *head;
      int a[8]={1,2,3,4,5,6,7,8};
      head = CreatLink(a,8);
      printLink(head);
      getch();
}