头文件
#define datatype int
struct stacknode
{
int num;//编号
datatype data;//数据
struct stacknode *pNext;//指针域,指针域存放指向下一个结点的指针,以实现链表彻底线型结构
};
struct stacknode *init(struct stackonde *phead);//初始化
struct stacknode *push(struct stacknode *phead, int num, datatype data);//进栈
struct stacknode *pop(struct stacknode *phead, struct stacknode *poutdata);//出栈
struct stacknode *freeall(struct stacknode *phead);//释放
struct stacknode *printfall(struct stacknode *phead);//打印
源文件
#include"stacklinknode.h"
#include<stdio.h>
#include<stdlib.h>
struct stacknode *init(struct stackonde *phead)//初始化
{
return NULL;
}
struct stacknode *push(struct stacknode *phead, int num, datatype data)//进栈
{
struct stacknode *pnewnode = (struct stacknode*)malloc(sizeof(struct stacknode));//创建节点
pnewnode->data = data;
pnewnode->num = num;
pnewnode->pNext = NULL;//开辟节点并赋值
if (phead == NULL)
{
phead = pnewnode;
}
else
{
struct stacknode *p = phead;
while (p->pNext != NULL)
{
p = p->pNext;
}
p->pNext = pnewnode;
}
return phead;
}
struct stacknode *printfall(struct stacknode *phead)//打印
{
//递归
if (phead == NULL)
{
return NULL;
}
else
{
printf("%d,%d,%p,%p\n", phead->data, phead->num, phead, phead->pNext);
printfall(phead->pNext);
}
}
struct stacknode *pop(struct stacknode *phead, struct stacknode *poutdata)//出栈
{
if (phead == NULL)
{
return NULL;
}
else if (phead->pNext == NULL)
{
poutdata->data = phead->data;
poutdata->num = phead->num;
free(phead);
phead = NULL;
return phead;
}
else
{
struct stacknode *p = phead;
while (p->pNext->pNext != NULL)
{
p = p->pNext;//循环到倒数第二个节点
}
poutdata->data = p->pNext->data;
poutdata->num = p->pNext->num;
free(p->pNext);
p->pNext = NULL;
return phead;
}
}
struct stacknode *freeall(struct stacknode *phead)//释放
{
if (phead == NULL)
{
return NULL;
}
else
{
struct stacknode *p1, *p2;
p1 = phead;//头节点
while (p1->pNext != NULL)
{
p2 = p1->pNext;//保存下一个节点
p1->pNext = p2->pNext;//跳过p2
free(p2);
}
free(phead);
return NULL;
}
}