單鏈表的創建過程有以下幾步:
1 ) 定義鏈表的數據結構;
2 ) 創建一個空表;
3 ) 利用malloc ( )函數向系統申請分配一個節點;
4 ) 將新節點的指針成員賦值爲空。若是空表,將新節點連接到表頭;若是非空表,將新
節點接到表尾;
5 ) 判斷一下是否有後續節點要接入鏈表,若有轉到3 ),否則結束;
//
// main.c
// simple-list
//
// Created by DOLFVE on 15-4-15.
// Copyright (c) 2015年 DOLFVE. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>/*含malloc()的頭文件*/
struct node
{
int num;
struct node *next;
};
int main() {
struct node *create();
void print();
struct node *head;
head = NULL;
head = create(head);
print(head);
}
struct node *crete(struct node *head)//返回的是與節點相同類型的指針
{
struct node *p1, *p2;
//①利用malloc()函數向系統申請分配一個節點
p1 = p2 = (struct node*)malloc(sizeof(struct node));//新節點
// printf("p1 = %d\n", p1);
scanf("%d",&p1->num);//輸入節點的值
p1->next = NULL;//將新節點的指針置爲空
while (p1->num > 0)//輸入的節點數值大於0
{
if (head == NULL) {
head = p1;//如果是空表,就接入表頭
}
else{
p2->next = p1;//非空表,就接到表尾
}
p2 = p1;
p1 = (struct node*)malloc(sizeof(struct node));
// printf("p2 = %d\n", p2);
scanf("%d", &p1->num);//輸入節點的值
//判斷是否有後續節點要接入鏈表,若有,就接入①,否則結束
}
// printf("p2->next = %d\n", p2->next);
return head;
}
void print (struct node *head)//輸出以head爲頭的鏈表各節點的值
{
struct node *temp;
temp = head;//取得鏈表的頭指針
while (temp != NULL)//只要是非空表
{
printf("%6d", temp->num);//輸出鏈表節點的值
temp = temp->next;//跟蹤鏈表增長
}
}