单链表的创建过程有以下几步:
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;//跟踪链表增长
}
}