您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法学习之栈及栈的相关操作

2011-04-23 10:42 232 查看
栈是一种将插入和删除操作限制在一端的表,有时也成为LIFO表;栈的操作核心是使用一个栈顶指针top指向栈顶元素。

栈中有两个总要的操作就是Push和pop,进栈和出栈操作。

栈也可以使用两种方式建立,数组方法和链表方法。当然数组实现是连续存储的,但是使用起来需要预先估计数组的大小。链表实现是非连续

存储的,使用相对灵活。

下面是本人在学习的时候将栈以数组和链表两种方法进行实现的代码。

链表实现code:

/***************************************************************************/
/*********************栈的非连续存储结构实现(链表实现)**********************/
/*********************Shanghai Jiaotong EE zhouguiyin***********************/
#include <iostream>
using namespace std;
typedef int Elemtype;
class Stackitem {
public:                                     //定义栈的节点结构
Elemtype data;
Stackitem *next;
};
class Stack {
public:
Stack(){top=NULL;}                  //构造函数,将TOP初始化为NULL
~Stack(){
while (top!=NULL) {         //析构函数,这个一定要有
Stackitem *L =top;
top=top->next;
delete L;}
}
void Push(Elemtype);                //压栈
void Isempty();                     //判断栈空
Elemtype Pop();                     //出栈并取栈顶元素
void Print();                       //打印栈中的元素
private:
Stackitem *top;
};
void Stack::Push(Elemtype x) {
Stackitem *p = new Stackitem;
p->data = x;
p->next =top;
top=p;
}
void Stack::Isempty() {
if(top==NULL)
cout<<"Stack is empty"<<endl;
else
cout<<"Stack is non-empty"<<endl;

}
Elemtype Stack::Pop() {
Elemtype y;
if (top==NULL)
cout<<"栈已空,无法弹栈"<<endl;
else{
Stackitem *sp = top;
y = top->data;
top = top->next;
delete sp;
}
return y;
}
void Stack::Print() {
if (top==NULL)
cout<<"栈已空,无元素输出"<<endl;
else{
Stackitem *iter = top;        //这里打印元素要重新顶一个一个指针
while(iter!=NULL) {           //,不要top指针!!!
cout<<iter->data<<endl;
iter=iter->next;
}
}
}
int main() {
Stack s;
for(int i=1;i!=7;i++)
s.Push(i);
s.Print();
Elemtype a1 = s.Pop();
Elemtype a2 = s.Pop();
cout<<a1<<endl;
cout<<a2<<endl;
s.Print();
s.Isempty();
}


下面是基于数组实现的code:

]/***************************************************************************/
/*********************栈的顺序存储结构实现(数组实现)**********************/
/*********************Shanghai Jiaotong EE zhouguiyin***********************/
#include <iostream>
using namespace std;
const int size=10;
typedef int Elemtype;
Elemtype y;
class Stack {
public:
Stack(){top=0;}
~Stack(){}
void Push(Elemtype);
void Set_empty(){top=0;}
bool Isempty();
Elemtype Pop();
void Print();
private:
int top;
Elemtype stack[size];
};
void Stack::Push(Elemtype x) {
if (top == size-1)
cout<<"存储空间已满,有溢出危险"<<endl;
else{
top++;
stack[top]=x;
}
}
bool Stack::Isempty() {
return(top==0);
}
Elemtype Stack::Pop() {
if (top==0)
cout<<"栈已空,无法弹栈"<<endl;
else{
y=stack[top];
top--;
}
return y;
}
void Stack::Print() {
if (top==0)
cout<<"栈已空,无元素输出"<<endl;
else{
for(int i=top;i>=1;i--)
cout<<"stack["<<i<<"] = "<<stack[i]<<endl;
}
}
int main() {
Stack s;
bool X;
for(int i=1;i!=7;i++)
s.Push(i);
s.Print();
Elemtype a1 = s.Pop();
Elemtype a2 = s.Pop();
cout<<a1<<endl;
cout<<a2<<endl;
s.Print();
cout<<(X=s.Isempty())<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: