链栈(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();
}
运行截图: