问题描述:创建单链表,实现输入元素,通过尾部插入的方式插入链表。
算法思路:
一 创建链表函数最终返回头结点的地址:实现分为三步走
1 申请内存;
2 赋值;
3 返回头结点地址
二 创建尾部插入函数
1建一个新结点(和创建链表的步骤差不多:申请内存之后进行赋值)
2 找尾结点
3 尾部插入
代码实现:
实现一个功能函数需要三个文件(三个文件在同一目录)。
linklist.h(定义顺序表)
linklist.c(实现接口函数)
test.c(主函数实现)
linklist.h
主要是定义结点结构体及指针;
定义创建链表函数、尾部插入函数和链表展示函数。
typedef int data_t;
//节点定义
typedef struct node{
data_t data;
struct node * next;
}listnode, *linklist;
//创建链表
linklist list_create();
int list_tail_insert(linklist H, data_t value);//head
int list_show(linklist H);
linklist.c
主要对list_create()链表创建函数、
list_tail_insert(linklist H, data_t value)尾部插入函数、
int list_show(linklist H)链表遍历展示函数、三个函数进行实现。
#include <stdio.h>
#include "linklist.h"
#include <stdlib.h>
linklist list_create(){
linklist H;
H = (linklist)malloc(sizeof(listnode));
if (H == NULL){
printf("malloc failed\n");
return H;
}
H->data = 0;
H->next = NULL;
return H;
}
int list_tail_insert(linklist H, data_t value){
//判断链表是否创建成功
if (H == NULL){
printf("H is NULL\n");
return -1;
}
//1 new node p
linklist p;
linklist q;
if ((p = (linklist)malloc(sizeof(listnode))) == NULL){
printf("malloc failed\n");
return -1;
}
p->data = value;
p->next = NULL;
//2 locate tail node
q = H;
while (q->next != NULL){
q = q->next;
}
//3 insert
q->next = p;
return 0;
}
int list_show(linklist H){
linklist p;
if (H == NULL){
printf("H is NULL\n");
return -1;
}
p = H;
while(p->next != NULL){
printf("%d ", p->next->data);
p = p->next;
}
puts("");
return 0;
}
test.c
主函数的实现
#include <stdio.h>
#include "linklist.h"
int main(int argc, const char *argv[])
{
linklist H;
int value;
H = list_create();
if (H == NULL)
return -1;
printf("input:");
while (1){
scanf("%d", &value);
if (value == -1){
break;
}
list_tail_insert(H, value);
printf("input:");
}
list_show(H);
return 0;
}
编译运行:
gcc *.c
./a.out
运行结果:
由上述结果可知,通过用户输入元素,在链表尾部成功插入各个元素。