|
linklist.h
#include<stdio.h>
#include<stdlib.h>
struct linknode
{
int data;
struct linknode * pnext;
};
typedef struct linknode node; //简化类型
void init(node *phead);//初始化头结点
node * addback(node* phead, int data); //尾部添加节点
void addhead(node**pphead, int data); //头部插入节点
void showall(node*phead);//显示
link.c
#include"linklist.h"
void init(node *phead)//初始化头结点
{
phead->pnext = NULL; //初始化
phead->data = 0; //初始化
}
//尾插,改变一个指针,需要指针的地址,用返回值给指针赋值
node* addback(node* phead, int data) //尾部添加节点
{
node*pnew = malloc(sizeof(node)); //为新节点分配内存
pnew->data = data; //赋值
pnew->pnext = NULL;
if (phead==NULL)
{
phead = pnew;
}
else
{
node *ptemp = phead;//备份头结点
while (ptemp->pnext != NULL)
{
ptemp = ptemp->pnext;
}
ptemp->pnext = pnew; //链接
}
return phead;
}
void addhead(node**pphead, int data) //头部插入节点
{
node*pnew = malloc(sizeof(node)); //为新节点分配内存
pnew->data = data; //赋值
pnew->pnext = NULL;
if (*pphead == NULL)
{
*pphead = pnew;
}
else
{
pnew->pnext = *pphead;
*pphead = pnew;
}
}
void showall(node*phead)//显示
{
if (phead==NULL)
{
return;
}
else
{
printf("%d %p %p\n", phead->data, phead, phead->pnext);
showall(phead->pnext);//跳到下一个节点
}
}
main.c
头插流程图#include"linklist.h"
void main()
{
node*phead=NULL;//头结点不分配内存
//init(phead); 不需要
phead=addback(phead, 11);
phead = addback(phead, 12);
phead = addback(phead, 13);
phead = addback(phead, 14);
phead = addback(phead, 15);
addhead(&phead, 20);
addhead(&phead, 21);
addhead(&phead, 19);
showall(phead);
system("pause");
}
运行结果:
尾插流程图 |
浙公网安备 33010602011771号