运用数组结构来构建的线性栈就是顺序栈。
本例实现了顺序栈的初始化、打印栈、入栈、出栈、判断栈空等操作。
#include<iostream>
using namespace std;
const int MAXSIZE=1000;
typedef struct{
int data[MAXSIZE];
int top;
}sqstack;
void initstack(sqstack *s);
void print(sqstack s);
void push(sqstack *s,int x);
int pop(sqstack *s);
bool stacknull(sqstack s);
int main(){
sqstack p;
/*以下是测试代码
initstack(&p);
cout<<stacknull(p)<<endl;
push(&p,1);
push(&p,2);
push(&p,3);
print(p);
cout<<pop(&p)<<endl;
print(p);
cout<<stacknull(p)<<endl;
*/
return 0;
}
void initstack(sqstack *s){
(*s).top=-1;
}
void print(sqstack s){
while(s.top>-1){
printf("%d ",s.data[s.top]);
s.top--;
}
return ;
}
void push(sqstack *s,int x){
if((*s).top==MAXSIZE-1){
printf("Error:stack over");
}
(*s).top++;
(*s).data[(*s).top]=x;
}
int pop(sqstack *s){
if((*s).top==-1)
printf("Error:stack null");
int x=(*s).data[(*s).top];
(*s).top--;
return x;
}
bool stacknull(sqstack s){
if(s.top==-1) return true;
else return false;
}
运用数组结构来构建的线性栈就是链栈。
本例实现了链栈的判断栈空、获取栈顶元素、入栈、出栈等操作。
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node * next;
}LinkStack;
int StackEmpty(LinkStack *top);
int GetTop(LinkStack *top);
LinkStack *Push(LinkStack *top,int x);
LinkStack *Pop(LinkStack *top);
int main(){
LinkStack *p;
/*以下是测试代码
p=Push(p,1);
p=Push(p,2);
p=Pop(p);
p=Pop(p);
*/
return 0;
}
int StackEmpty(LinkStack *top){
if(top) return false;
else return true;
}
int GetTop(LinkStack *top){
if(!top){
printf("/n链栈是空的!");
return 0;
}
else return top->data;
}
LinkStack *Push(LinkStack *top,int x){
LinkStack *p;
p=(LinkStack *)malloc(sizeof(LinkStack));
p->data=x;
p->next=top;
top=p;
return top;
}
LinkStack *Pop(LinkStack *top){
LinkStack *p;
if(!top){
printf("/n链栈是空的!");
return NULL;
}
p=top;
printf("%d\n",p->data);
top=top->next;
free(p);
return top;
}