一、用顺序表实现的顺序栈
#include<iostream>
#include<cstdio>
using namespace std;
//栈的相关操作以及实现,包括初始化、判空、判满、增(push)、删(pop)、查(getpop);栈不涉及“改”的问题。//栈的的数据结构的定义 #define MaxSize 100 typedef struct{ //顺序栈 int data[MaxSize]; int top; }SqStack; void InitStack(SqStack &S){ //栈的初始化 S.top = -1; //注意在这里是让栈顶指针指向当前数据的上一个地址 } bool IsEmpty(SqStack S){ //判断栈是否为空 return S.top == -1; } bool IsFull(SqStack S){ return S.top == MaxSize-1; } bool Push(SqStack &S,int x){ //入栈操作 //栈满不可以插入元素 if(IsFull(S)) return false; S.data[++S.top] = x; return true; } bool Pop(SqStack &S, int &x){ //出栈操作 //判断栈是否为空 if(IsEmpty(S)) return false; x = S.data[S.top--]; return true; } bool GetPop(SqStack S,int &x){ if(IsEmpty(S)) return false; x = S.data[S.top]; return true; } int main(){ //用来测试以上函数是否可以正确运行 SqStack S; int x; InitStack(S); for(int i = 0; i < 5; i++){ Push(S,i); } while(Pop(S,x)){ printf("%d ",x); } return 0; }
用链表实现的链栈
1,带头节点的链栈
#include<iostream> #include<cstdio> using namespace std; //用链表实现的链栈(带头节点) //基本的数据定义 typedef struct LinkNode{ int data; struct LinkNode *next; }*LiStack; LiStack L = (LiStack)malloc(sizeof(LiStack)); //链栈的初始化 void InitLiStack(LiStack &S){ LiStack L = (LiStack)malloc(sizeof(LiStack)); L->next = NULL; } //无需判空和判满 //增加元素 bool Push(LiStack &S,int x){ LiStack p = (LiStack)malloc(sizeof(LiStack)); //内存空间不足 if(p == NULL) return false; p->data = x; p->next = L->next; L->next = p; return true; } //删除元素 bool Pop(LiStack S,int &x){ if(L->next == NULL){ //链栈空 return false; } x = L->next->data; L->next = L->next->next; return true; } //得到栈顶元素 bool GetTop(LiStack S,int x){ //栈空 if(L->next ==NULL) return false; x = L->next->data; return true; } int main(){ //Test LiStack S; int x; InitLiStack(S); for(int i= 1; i < 5; i++){ Push(S,i); } while(L->next != NULL){ Pop(S,x); printf("%d ",x); } return 0; }
2.不带头节点的链栈
#include<iostream> #include<cstdio> using namespace std; //用链表实现的链栈(不带头节点) //基本的数据定义 typedef struct LinkNode{ int data; struct LinkNode *next; }*LiStack; LiStack L; //链栈的初始化 void InitLiStack(LiStack &S){ L = NULL; } bool Push(LiStack &S,int x){ LiStack p = (LiStack)malloc(sizeof(LiStack)); //内存分配失败 if(p == NULL) return false; p->data = x; //如果插入的是第一个节点,需要将next指针置空 if(L == NULL){ p->next = NULL; } p->next = L; L = p; return true; } //链栈的Pop操作 bool Pop(LiStack &S,int &x){ //出栈需要释放节点 LiStack p; //如果链栈为空,则栈为空 if(L == NULL) return false; p = L; x = p->data; L = p->next; free(p); return true; } //获得栈顶元素 bool GetPop(LiStack S,int &x){ if(L == NULL) return false; x = L->data; return true; } int main(){ //测试使用 LiStack S; int x; InitLiStack(S); for(int i =1; i < 10; i++){ x = random()%1000; printf("%d\n",x); Push(S,x); } while(Pop(S,x)){ printf("%d ",x); } return 0; }