C++实现顺序和链式堆栈

C++实现顺序和链式堆栈


定义

  • 堆栈:具有一定操作约束的线性表
  • 只在一段(栈顶,Top)做插入、删除
  • 插入数据:入栈(Push)
  • 删除数据:出栈(Pop)
  • 后入先出:Last In First Out

抽象数据类型描述

  • 类型名称:堆栈(Stack)
  • 数据对象集:一个有0个或者多个元素的有穷线性表
  • 操作集:长度为MaxSize的堆栈
    • MaxHeap Create( int MaxSize ):创建一个空的最大堆。
    • Boolean IsFull( MaxHeap H ):判断最大堆H是否已满。
    • Insert( MaxHeap H, ElementType item ):将元素item插入最大堆H
    • Boolean IsEmpty( MaxHeap H ):判断最大堆H是否为空。
    • ElementType DeleteMax( MaxHeap H ):返回H中最大元素
    • void Push():在栈顶增加元素
    • void pop(): 移除栈顶元素(不会返回栈顶元素的值)

  • 顺序表实现栈
    • 栈顶为顺序表的尾部
    • 栈低为顺序表的首部
//顺序栈
#include<iostream>
using namespace std;
const int MaxSize = 100;

template <class T>
class stack
{
public:
	stack()
	{
		top = -1;
	}
	void push(T x);
	T pop();
	int empty();
	void printstack();
private:
	int top;
	T data[MaxSize];
};

template <class T>

int stack<T>::empty()
{
	if (top == -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

template <class T>

void stack<T>::push(T x)
{
	if (top == MaxSize - 1)
		throw "栈空间已满";
	data[++top] = x;
}
template <class T>
T stack<T>::pop()
{
	if (top == -1) throw"栈已空";
	T x;
	x = data[top--];
	return x;
}

template <class T>
void stack<T>::printstack()
{
	if (top == -1) throw"这是空栈";
	for (int i=0; i<=top;i++)
	{
		cout << data[i] << endl;
	}
		
} 

int main()
{
	stack<int> s;
	s.push(1);
	s.push(2);
	s.printstack();
	cout << s.pop() << endl;
	s.printstack();
	system("pause");
}

  • 链表实现栈
  • 注意:
    • 栈顶为链表的头
    • 每次push都需要将node设置为top(链表的头)
#include<iostream>
using namespace std;
class Node
{
public:
	Node(int x)
	{
		data = x;
		next = NULL;
	}
	int data;
	Node *next;
};

class stack
{
public:
	stack()
	{
		top = NULL;
		buttom = NULL;
	}
	void push(int x);
	void pop();
	void printstack();
private:
	Node *top;
	Node *buttom;
	int count=0;
};

void stack::push(int x)
{
	if (top == NULL)
	{
		Node *temp = new Node(x);
		top = temp;
		count++;
	}
	else
	{
		Node *temp = new Node(x);
		temp->next = top;
		top = temp;
		count++;
	}
}

void stack::pop()
{
	if (top == NULL)
		throw"栈已为空";
	else if(count == 1)
	{
		Node *temp = top;
		top = top->next;
		delete temp;
		count--;
	}
	else
	{
		top = top->next;
		count--;
	}

}

void stack::printstack()
{
	Node *p = top;
	while (p != NULL)
	{
		cout << p->data;
		cout << " ";
		p = p->next;
	}
	cout << endl;
}

int main()
{
	stack s;
	s.push(1);
	s.push(2);
	s.push(2);
	s.printstack();
	s.pop();
	s.printstack();
	system("pause");
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值