顺序栈:话不多说直接上代码
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<assert.h> using namespace std; const int maxsize=50; //注意节点的内容即可 typedef struct { int data[maxsize]; int top; }stack; //初始化 void initStack(stack* p){ p->top=-1; } //判空 bool empty(stack* p){ if(p->top>=0) return false; else return true; } //进栈 void push(stack *p,int num){ if(p->top==maxsize-1){ cout<<"栈满"<<endl; return; } else{ p->top++; p->data[p->top]=num; } } //取栈顶元素 int top(stack* p){ if(empty(p)){ cout<<"stack is empty"<<endl; return NULL; }else{ return p->data[p->top]; } } //退栈 int pop(stack* p){ if(empty(p)){ cout<<"stack is empty"<<endl; return NULL; } else{ p->top--; return(p->data[p->top+1]); } } int main(){ stack* p=new stack; int a[5]={1,5,3,12,31}; initStack(p); if(empty(p)) cout<<"该栈是空栈"<<endl; for(int i=0;i<5;i++) push(p,a[i]); cout<<top(p)<<endl; cout<<pop(p)<<endl; system("pause"); return 1; }
链栈:只能在链表头部进行操作,所以没有必要附加头结点,栈顶指针就是链表的头指针。其实也可以带头结点,
可以按照需求来定义,话不多述,直接代码
typedef struct node{ int data; struct node* next; }linkstack; void initStack(linkstack* p){ p->next=NULL; } bool empty(linkstack* p){ if(p->next==NULL) return true; else return false; } void push(linkstack* p,int num){ linkstack *q=new linkstack; if(q==NULL) return; q->data=num; //栈使用的是头插法 q->next=p->next; p->next=q; } int gettop(linkstack* p){ if(p->next==NULL){ cout<<"栈为空"<<endl; return NULL; } else{ return p->next->data; } } int pop(linkstack* p){ if(p->next==NULL){ cout<<"栈为空"<<endl; return NULL; } linkstack* q; int data; q=p->next; data=p->next->data; p->next=q->next; free(q);//释放内存 return data; } int main(){ linkstack* p=new linkstack; int a[5]={1,12,22,31,2}; initStack(p); if(empty(p)) cout<<"该栈是空栈"<<endl; for(int i=0;i<5;i++) push(p,a[i]); cout<<"栈首元素是:"<<gettop(p)<<endl; while(!empty(p)){ cout<<pop(p)<<"出栈"<<endl; } system("pause"); return 1; }