链栈
- 链栈:使用链表来实现栈,链表中的元素存储在不连续的地址,由于是动态申请内存,所以我们可以以非常小的内存空间开始,另外当某个项不使用时也可将内存返还给系统。
- 链式存储结构是采取链表指针来指示数据的存储位置,这就可以是在内存中随意的存储,没有必须连续储存空间的要求,对于内存的要求相对较容易。
链栈结构
typedef struct Node
{
ElemType data;
struct Node* next;
}Node,Stack,*pStack;
整体结构
Stack.h函数声明
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node* next;
}Node,Stack,*pStack;
void init(pStack pst);
Node* buyNode(ElemType val);
void push(pStack pst, ElemType val);
int empty(pStack pst);
int pop(pStack pst);
int gettop(pStack pst, ElemType* prt);
void destory(pStack pst);
代码实现
Stack.cpp代码的实现
#include<stdio.h>
#include<stdlib.h>
#include"Stack.h"
void init(pStack pst)
{
if (pst != NULL)
{
pst->next = NULL;
}
}
Node* buyNode(ElemType val)
{
Node* pnewnode = (Node*)malloc(sizeof(Node));
pnewnode->data = val;
pnewnode->next = NULL;
return pnewnode;
}
void push(pStack pst, ElemType val)//元素做一个链表的头插
{
Node* pnewnode = buyNode(val);
pnewnode->next = pst->next;
pst->next = pnewnode;
}
int empty(pStack pst)
{
return pst->next == NULL ? 1 : 0;
}
int pop(pStack pst)//头插 栈的出栈
{
if (empty(pst))
{
return 0;
}
Node* pCur = pst->next;//第一个数据结点
pst->next = pCur->next;
free(pCur);
return 1;
}
int gettop(pStack pst, ElemType* prt)
{
if (empty(pst))
{
return 0;
}
*prt = pst->next->data;//第一数据结点的数据
return 1;
}
void destory(pStack pst)
{
Node* pCur = pst->next;//第一数据结点
Node* pNext = NULL;
while (pCur != NULL)
{
pNext = pCur->next;
free(pCur);
pCur = pNext;
}
pst->next = NULL;
}
程序测试
main.cpp代码测试
#include"Stack.h"
int main()
{
Stack st;
init(&st);
for (int i = 0; i < 5; i++)
{
push(&st, i + 1);//
}
int rt = 0;
int flag = gettop(&st, &rt);
if (flag)
{
printf("rt : %d\n", rt);
pop(&st);
}
return 0;
}