堆栈

顺序储存

#include<iostream>
using namespace std;
#define MaxSize 10
const ERROR=0;
const TRUE=1;
typedef int ElemType;
typedef struct Snode
{
	ElemType data[MaxSize];
	int Top;
}Snode;
void Push(Snode *Ptrs,ElemType Item)//入栈
{
	if(Ptrs->Top==MaxSize)
	{
		cout<<"堆栈满";
		return ;
	}
	else
	{
		Ptrs->data[++(Ptrs->Top)]=Item;
		return ;
	}
}
ElemType Pop(Snode *Ptrs,)//出栈
{
	if(Ptrs->Top==-1)
	{
		cout<<"堆栈空";
		return ERROR;
	}
	else
	{
		return (Ptrs->data)[(Ptrs->Top)--];
	}
}

链式存储

#include <iostream>
using namespace std;
#define MaxSize 10
typedef int ElemType;

typedef struct Snode {
	ElemType data;
	struct Snode *next;
} Snode;

Snode *CreatStake() { //创建堆栈头节点
	Snode *s = new Snode;
	s->next = NULL;
	s->data = 0;
	return s;
}

bool EmptyNode(Snode *s) { //判断堆栈是否为空
	if (s->next == NULL)
		return true;
	return false;
}

void Push(ElemType item, Snode *s) { //将元素压入堆栈,从头压入
	Snode *temp = new Snode;
	temp->data = item;
	temp->next = s->next;
	s->next = temp;
}

ElemType Pop(Snode *s) { //删除并返回栈顶元素,取头
	Snode *FirstCell = new Snode;
	ElemType TopElem;
	if (EmptyNode(s)) {
		cout << "堆栈空";
		return 0;
	} else {
		FirstCell = s->next;
		s->next = FirstCell->next;
		TopElem = FirstCell->data;
		free(FirstCell);
		return TopElem;
	}
}

void DispStake(Snode *s) {//递归遍历
	if (s == NULL)
		return ;
	else {
		cout << s->data << " ";
		DispStake(s->next);
	}
}
posted @ 2022-01-27 10:50  帝宝单推人!  阅读(31)  评论(0)    收藏  举报