数据结构
栈
顺序栈
顺序栈特点是有栈顶指针top和栈顶指针base
栈为空时top=base
top-base的值表示栈中当前元素个数,为零时表示为空栈
top一直在栈顶元素的上一个位置
#include<stdio.h>
#include<stdlib.h>
//顺序栈
#define MAXSIZE 100
typedef int SElemType;
typedef struct{
SElemType *base; //栈底指针
SElemType *top; //栈顶指针
int stacksize; //栈可用最大容量
}SqStack;
//建立空栈
bool InitStack(SqStack &S){
S.base = (SElemType*)malloc(sizeof(SqStack)*MAXSIZE);
if(!S.base) return false;//分配空间失败则返回错误
S.top = S.base;//top初始为base表示空表
S.stacksize = MAXSIZE;//stacksize置为最大容量
return true;
}
//入栈
bool Push(SqStack &S, SElemType e){
if((S.top-S.base) == S.stacksize) return true; //栈满无法入栈
*(S.top) = e;
S.top++;//这两部也可以用*(S.top)++ = e
return true;
}
//出栈
bool Pop(SqStack &S, SElemType &e){
if(S.top==S.base) return false;//栈空无法Pop出元素
S.top--;
e = *(S.top);//这两部也可以简化为e = *(--S.top)
return true;
}
//取出顺序栈的栈顶元素
SElemType GetTop(SqStack S){
if(S.top!=S.base) {
return *(--S.top);
}
else return -1; //栈为空
}
int main(){
int i = 0;
SqStack S;
int elem = 0;
if(!InitStack(S)) printf("error\n");
for(; i<5; i++){
Push(S, i);
}
printf("%d \n", GetTop(S));
printf("\n");
for(i=0; i<5; i++){
Pop(S, elem);
printf("%d ", elem);
}
}
链栈
#include<stdio.h>
#include<stdlib.h>
typedef int SElemType;
typedef struct StackNode{
SElemType data;
struct StackNode *next;
}StackNode, *LinkStack;
//创建空栈
bool InitStack(LinkStack &S){
S = NULL; //栈顶指针置空
return true;
}
//入栈
bool Push(LinkStack &S, SElemType e){
LinkStack p = (LinkStack)malloc(sizeof(StackNode));
if(!p) return false;//分配空间失败
p->data = e;//赋值数据域
p->next = S;//插入元素至栈顶
S = p;// 修改栈顶指针为S
return true;
}
//出栈
bool Pop(LinkStack &S, SElemType &e){
if(!S) return false;//栈为空
LinkStack p = S;
e = p->data;//取出栈顶元素
S = S->next;//修改栈顶指针
free(p);//释放原栈顶空间
return true;
}
//取出栈顶元素,不修改栈顶指针
SElemType GetTop(LinkStack S){
if(S!=NULL){//栈不空
return S->data;
}
}
int main(){
int i=0;
SElemType elem = 0;
LinkStack S1 = NULL;
InitStack(S1);
for(; i<5; i++){
Push(S1, i);
}
printf("%d ", GetTop(S1));
printf("\n");
for(i=0; i<5; i++){
Pop(S1, elem);
printf("%d ", elem);
}
}