数据结构——顺序栈

#include <iostream>
using namespace std;

#define StackSize 10 //假定预分配的栈空间最多为100个元素
typedef
int DataType; //假定栈元素的数据类型为字符
typedef struct
{
DataType data[StackSize];
int top;
}SeqStack;

//初始化顺序栈
void init_seqstack(SeqStack *ss)
{
ss
->top=0;
}

//入栈
int Push_seqstack(SeqStack *ss,int x)
{
++(ss->top);
if(ss->top>StackSize)
{
cout
<<"栈满!"<<endl;
return 0;
}
else
{
ss
->data[ss->top]=x;
return 1;
}
}

//出栈
void Pop_seqstack(SeqStack *ss)
{
if(ss->top==0)
cout
<<"is empty!"<<endl;
else
cout
<<ss->data[ss->top--]<<endl;
}

//显示栈
void display_seqstack(SeqStack *ss)
{
if(ss->top==0)
cout
<<"is empty!";
else
{
int temp=ss->top;
while(temp!=0)
cout
<<ss->data[temp--]<<" ";
}
}

//取栈顶元素
int gettop_seqstack(SeqStack *ss)
{
return ss->data[ss->top];
}

//判栈空
int isempty_seqstack(SeqStack *ss)
{
return ss->top ? 1 : 0;
}

//查找元素
int search_seqstack(SeqStack *ss ,int x)
{
while(ss->top!=0)
if(ss->data[ss->top--]== x)
return 1;
return 0;
}

//置栈空
void clear_seqstack(SeqStack *ss)
{
//ss->top=0;
init_seqstack(ss);
cout
<<"置空成功!"<<endl;
}

int main()
{
SeqStack
*ss;
ss
=(SeqStack *) malloc(sizeof(SeqStack));
//初始化顺序栈
init_seqstack(ss);
//入栈
Push_seqstack(ss,15);
Push_seqstack(ss,
23);
Push_seqstack(ss,
54);
Push_seqstack(ss,
67);
Push_seqstack(ss,
32);
//显示栈
display_seqstack(ss);
cout
<<endl;

//出栈
Pop_seqstack(ss);
Pop_seqstack(ss);

//显示栈
display_seqstack(ss);
cout
<<endl;

//再入栈
Push_seqstack(ss,78);
Push_seqstack(ss,
43);
//显示栈
display_seqstack(ss);
cout
<<endl;

//取栈顶元素
cout<<"栈顶元素时: "<<gettop_seqstack(ss)<<endl;

//判栈空
if(isempty_seqstack(ss)==0)
cout
<<"is empty!"<<endl;
else
cout
<<"no"<<endl;

//查找元素
if(search_seqstack(ss,99))
cout
<<"yes!find it."<<endl;
else
cout
<<"is not exist."<<endl;
//置栈空
cout<<"置空线性栈? ";
clear_seqstack(ss);
display_seqstack(ss);

return 0;
}

 

posted @ 2010-07-22 18:45  忧国忧铭  Views(334)  Comments(0)    收藏  举报