栈——链栈

链栈

  • 链栈:使用链表来实现栈,链表中的元素存储在不连续的地址,由于是动态申请内存,所以我们可以以非常小的内存空间开始,另外当某个项不使用时也可将内存返还给系统。
  • 链式存储结构是采取链表指针来指示数据的存储位置,这就可以是在内存中随意的存储,没有必须连续储存空间的要求,对于内存的要求相对较容易。

链栈结构

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值