stack.h
#pragma once
#include <stdio.h>
#include<stdlib.h>
typedef struct tag //定义栈的节点结构体
{
int val;
struct tag* pnext;
}node, * pnode;
typedef struct { //定义栈结构体
int size;
pnode phead;
}Stack, * pStack;
void initStack(pStack stack) //初始化一个栈
{
memset(stack, 0, sizeof(stack));
}
void pop(pStack stack) //弹栈
{
if (!stack->phead) {
printf("stack is empty");
return;
}
pnode pcur;
pcur = stack->phead;
stack->phead = pcur->pnext;
free(pcur);
pcur = NULL; //避免pcur变成野指针
}
void push(pStack stack,int val) //压栈
{
pnode pnew = (pnode)calloc(1, sizeof(node));
pnew->val = val;
pnew->pnext = stack->phead;
stack->phead = pnew;
stack->size++;
}
int size(pStack stack) { //返回栈的大小
return stack->size;
}
int top(pStack stack) { //返回栈顶值
if (!stack->size) {
printf("stack is empty");
return -1;
}
return stack->phead->val;
}
main.c
#include"stack.h"
int main()
{
Stack stack;
initStack(&stack);
push(&stack, 5);
push(&stack, 10);
pop(&stack);
int ret = top(&stack);
return 0;
}
栈的顺序存储 C++
#include <stdio.h>
#include<stdlib.h>
#include<string>
#define Maxsize 50
typedef int ElemType;
typedef struct {
ElemType data[Maxsize];
int top;
}SqStack;
void initStack(SqStack &stack) {
stack.top = -1;
}
bool pop(SqStack& S, ElemType& x) {
if (S.top == -1)
return false;
x = S.data[S.top--];
return true;
}
bool push(SqStack& stack, ElemType val) { //顺序存储 压栈
if (stack.top == Maxsize - 1)
return false;
stack.data[++stack.top] = val;
return true;
}
bool GetTop(SqStack& S, ElemType& x) {
if (S.top == 1)
return false;
x = S.data[S.top];
return true;
}
int main()
{
SqStack stack;
int x,ret;
initStack(stack);
push(stack, 5);
push(stack, 10);
pop(stack,x);
GetTop(stack,ret);
return 0;
}