1. 程式人生 > >一起學習C語言之建立連結串列

一起學習C語言之建立連結串列

一、建立單向連結串列

開啟 VC6.0,建立一個c檔案,引入標頭檔案如下:

#include <stdio.h>
#include <malloc.h>

二、宣告一個struct結構體,定義每個節點

struct LNode
{
int data;
struct LNode *next;
};

三、定義一個函式產生連結串列,並返回連結串列的頭地址:


struct LNode *create(int n)
{
int i;
struct LNode *head, *p1, *p2;
int a;
head = NULL;
printf("輸入整數:\n");
for(i=n; i>0; i--)
{
p1 = (struct LNode*)malloc(sizeof(struct LNode));//開闢節點空間 
scanf("%d", &a);
p1->data = a;
if(head ==  NULL)//第一個節點
{
head = p1;//頭存p1節點
p2=p1;//p2存p1節點
} else {
p2->next = p1;
p2=p1;//它的意思是p2的地址更新為新建的p1的地址
}
}
p2->next = NULL;
return head;
}
四、定義一個main函式,呼叫產生連結串列的creat函式,並將建立的連結串列內容輸出。

void main()
{
int n;
struct LNode *q;
printf("輸入你想建立的節點個數:");
scanf("%d", &n);
q = create(n);
printf("結果是:\n");
while(q)
{
printf("%d  ", q->data);
q = q->next;
};
printf("\n");
}