数据结构——栈

1. 概念

栈(stack)是一种形式的表,在这种数据结构中,所有的元素插入和删除都在表的一端进行,这一端称为栈顶(top)。向栈中增加一项时,叫入栈(push),在栈中删除一项时,称为出栈(pop)。最后压入到栈中的项总是最先弹出。这种性质叫后进先出(last in, first out, LIFO)。

比如食堂堆叠起来的餐盘,就餐时总是从最顶部拿走一个餐盘,工作人员将餐盘返回时放在堆顶上。最后放的餐盘在堆顶上,会最先被拿走;而最先放的餐盘在堆底,会最后一个被使用。(假设每次只存取一个)

2. 初体验

首先直接使用c++标准模板库(STL)中的stack,实现反转表(Reversing a List),体会stack的功能。

#include <iostream>
#include <stack>

using namespace std;

int main(){
	int n;
	double item;
	stack<double> numbers;
	cout << "输入数量n,并输入n个数,这些数会逆序输出。" << endl;
	cin >> n;
	for(int i = 0; i < n; i++){
		cin >> item;
		numbers.push(item);
	}
	cout << endl;
	while(!numbers.empty()){
		cout << numbers.top() << " ";
		numbers.pop();
	}
}

复制

3. 栈的实现

3.1 Contiguous Stack

顺序栈,在内存中连续存储,在代码上的体现就是使用数组实现。

enum Error_code{success, underflow, overflow};

template <class Stack_entry>
class Stack{
public:
	Stack(int size = 10);
	~Stack();
	bool empty() const;
	bool full() const;
	Error_code pop();
	Error_code push(const Stack_entry &item);
	Error_code top(Stack_entry &item) const;
private:
	int size; // 最大容量 
	int top_; // 栈顶位置 
	Stack_entry* entries;
};

template <typename Stack_entry>
Stack<Stack_entry>::Stack(int s) 
	: size(s > 0 ? s : 10),
	  top_(-1),
	  entries(new Stack_entry[size]){
}

template <typename Stack_entry>
Stack<Stack_entry>::~Stack(){
	delete [] entries;
}

template <typename Stack_entry>
bool Stack<Stack_entry>::empty() const{
	return top_ == -1;
}

template <typename Stack_entry>
bool Stack<Stack_entry>::full() const{
	return top_ >= size - 1;
}

template <typename Stack_entry>
Error_code Stack<Stack_entry>::pop(){
	Error_code outcome = success;
	if(empty()){
		outcome = underflow;
	}else{
		top_--;
	}
	return outcome;
}

template <typename Stack_entry>
Error_code Stack<Stack_entry>::push(const Stack_entry &item){
	Error_code outcome = success;
	if(full()){
		outcome = overflow;
	}else{
		entries[++top_] = item;
	}
	return outcome;
}

template <typename Stack_entry>
Error_code Stack<Stack_entry>::top(Stack_entry &item) const{
	Error_code outcome = success;
	if(empty()){
		outcome = underflow;
	}else{
		item = entries[top_];
	}
	return outcome;
}

复制

3.2 Linked Stack

链式栈,在内存中不连续存储,在代码上的体现是使用链实现。

链式的实现方法可以节约内存,需要多少就分配多少,不像顺序栈那样一开始就要指定内存大小。

但链还需要存储指向下一节点的指针,在某种意义上减小了内存利用率,并且在出栈入栈操作时还需要进行释放内存和指针的赋值操作,效率较低

enum Error_code{success, underflow, overflow};

template <class Stack_entry>
class Stack{
public:
	Stack();
	~Stack();
	bool empty() const;
	Error_code pop();
	Error_code push(const Stack_entry &item);
	Error_code top(Stack_entry &item) const;
private:
	struct Node{
		Stack_entry entry;
		Node *next;
		Node(Stack_entry entry_, Node* next_ = NULL):
			entry(entry_), next(next_){
		}
	};
	Node *top_node; // 栈顶指针 
};

template <typename Stack_entry>
Stack<Stack_entry>::Stack() :
	  top_node(NULL){
}

template <typename Stack_entry>
Stack<Stack_entry>::~Stack(){
	Node *temp = top_node;
	while(temp != NULL){
		top_node = top_node->next;
		delete temp;
		temp = top_node;
	} 
}

template <typename Stack_entry>
bool Stack<Stack_entry>::empty() const{
	return top_node == NULL;
}

template <typename Stack_entry>
Error_code Stack<Stack_entry>::pop(){
	Error_code outcome = success;
	if(empty()){
		outcome = underflow;
	}else{
		Node *temp = top_node;
		top_node = top_node->next;
		delete temp;
	}
	return outcome;
}

template <typename Stack_entry>
Error_code Stack<Stack_entry>::push(const Stack_entry &item){
	Node *temp = new Node(item, top_node);
	Error_code outcome = success;
	if(temp == NULL){
		outcome = overflow;
	}else{
		top_node = temp;
	}
	return outcome;
}

template <typename Stack_entry>
Error_code Stack<Stack_entry>::top(Stack_entry &item) const{
	Error_code outcome = success;
	if(empty()){
		outcome = underflow;
	}else{
		item = top_node->entry;
	}
	return outcome;
}

复制

4. 相关算法

4.1 括号匹配

问题:输入一段带括号的字符串,判断其中的括号是否成对出现。

可以使用栈来实现,思路如下:

(1) 当遇到左括号时,入栈;

(2) 遇到右括号时

​ (2.1) 若栈为空,则不匹配,否则

​ (2.2) 判断一下栈顶是不是跟该右括号匹配,并将其出栈

(3) 循环(1)或(2)直到字符串结束,若最终没有出现不匹配的括号且栈为空,则所有括号成功匹配

代码实现如下: (注:这里使用了上述自定义的栈实现)

#include <iostream>
#include "stack.hpp"

using namespace std;

int main(){
	Stack<char> openings;
	char symbol;
	bool is_matched = true;
	while((symbol = cin.get()) != '\n'){
		if(symbol == '(' || symbol == '[' || symbol == '{'){ // 左括号 
			openings.push(symbol);
		}else if(symbol == ')' || symbol == ']' || symbol == '}'){ // 右括号
			if(openings.empty()){
				is_matched = false;
				cout << "括号 " << symbol <<" 不匹配。" << endl;
			}else{
				char top;
				openings.top(top);
				openings.pop();
				if(!(symbol == ')' && top == '('
					|| symbol == ']' && top == '['
					|| symbol == '}' && top == '{')){
					is_matched = false;
					cout << "括号 " << symbol <<" 不匹配。" << endl;
				}
			} 
		}
	}
	if(is_matched && openings.empty()){
		cout << "成功匹配";
	}else{
		cout << "匹配失败";
	}
}

复制

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

红红火火a

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值