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;
}