【数据结构】链栈

本文介绍了链栈的基本概念,并详细探讨了链栈的运算实现,包括如何在CC++中创建链栈模板。此外,文章还提供了一个实际的应用实例,展示了如何设计算法实现链栈的就地逆置,即将链栈中的元素顺序反转,这一过程不使用额外的数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链栈(linked stacks)

(1)运算实现

  头文件:

#ifndef QUEUE_H
#define QUEUE_H

#include <iostream>
using namespace std;

template <class Type>
struct node {
	Type data;
	node *next;
};

template <class Type> 
class stack {
public:
	stack();//构造函数用于初始化(C++11可以在类里面初始化)
	~stack();//析构函数用于释放所有空间
	bool empty();//判断栈是否为空
	void get_top(Type &x);//取栈顶
	void push(const Type x);//入栈
	void pop();//出栈
	int count();//返回链栈的元素个数
	void show();//打印链栈中的元素
	void reverse();//链栈的逆置
private:
	node<Type> *top;
};

template <class Type>
stack<Type>::stack() {
	top = NULL;
}
template <class Type>
bool stack<Type>::empty() {
	return top == NULL;
}
template <class Type>
void stack<Type>::get_top(Type &x) {
	if (!empty())
		x = top->data;
}
template <class Type>
void stack<Type>::push(const Type x) {
	node<Type> *u = new node<Type>;
	u->data = x;
	u->next = top;
	top = u;
}
template <class Type>
void stack<Type>::pop() {
	if (!empty()) {
		node<Type> *u = top;
		top = u->next;
		delete u;
	}
}
template <class Type>
int stack<Type>::count() {
	int count = 0;
	if (!empty()) {
		node<Type> *u = top;
		while (u != NULL) {
			++count;
			u = u->next;
		}
	}
	return count;
}
template <class Type>
void stack<Type>::show() {
	if (!empty()) {
		node<Type> *u = top;
		cout << "元素:";
		while (u != NULL) {
			cout << u->data << " ";
			u = u->next;
		}
		cout << endl;
	}
}
template <class Type>
void stack<Type>::reverse() {
	if (count() > 1) {
		node<Type> *u = top->next;
		node<Type> *v = u->next;
		top->next = NULL;
		while (v != NULL) {
			u->next = top;
			top = u;
			u = v;
			v = v->next;
		}
		u->next = top;
		top = u;
		cout << "\n逆置结果" << endl;
		show();
	}
	else cout << "\n元素个数小于2不能逆置!" << endl;
}
template <class Type>
stack<Type>::~stack() {
	while (!empty())
		pop();
}

#endif

(2)应用实例

  设计算法将链栈就地逆置,即将链栈中的各元素结点的后继指针倒置为指向其前驱结点。

#include"stack.h"

int main() {
	int x;
	stack<int> s;
	while (cin >> x)
		s.push(x);
	cin.clear();
	s.show();
	s.reverse();
	cin.get();
}
  运行截图:

  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值