数据结构——栈的基本操作

来源:互联网 发布:淘宝网红模特有哪些 编辑:程序博客网 时间:2024/05/16 08:41

顺序栈:

#include<bits/stdc++.h>#define MAX 100 //栈的最大值using namespace std;typedef int  SElemType;struct SqStack{   SElemType *base;    SElemType *top;    int  stacksize;};void menu(){printf("\t1 初始化\n");printf("\t2 入栈\n");printf("\t3 出栈\n");printf("\t4 是否为空栈\n");printf("\t5 退出\n");}void init(SqStack &s){s.base = (SElemType*)malloc(MAX * sizeof(SElemType));s.top = s.base;s.stacksize = MAX;}void push(SqStack &s, SElemType x){if(s.top - s.base >= s.stacksize)    {        s.base = (SElemType*)realloc(s.base, sizeof(SElemType) * s.stacksize * 2);        s.stacksize *= 2;    } *(s.top++) = x;}int Stack_pop(SqStack &s){if(s.top == s.base)    {        printf("Empty!\n");        return 0;    }s.top--;return 1;}void display(SqStack &s){if(s.top == s.base){    printf("Empty!\n");    return ;}    printf("base ----> top\n");for(int i = 0; s.base + i < s.top; i++)printf("%d ", *(s.base + i));    cout << endl;}void is_Empty(SqStack s){    if(s.top == s.base) puts("Yes");    else puts("No");}int main(){SqStack s;int num, now;while(1){menu();scanf("%d", &num);switch(num){case 1 : init(s); break;case 2 : printf("Input\n"); scanf("%d",&now); push(s, now);  display(s); break;case 3 : if(Stack_pop(s)){    printf("after delete\n");    display(s);            } break;            case 4: is_Empty(s);}if(num == 5) break;}return 0;}



链栈:

#include<bits/stdc++.h>#define N 100using namespace std;typedef int  SElemType;typedef struct snode{  SElemType data;  struct snode *next;  struct snode *pre;}StackNode, *LinkStack;void menu(){printf("\t1 初始化\n");printf("\t2 入栈\n");printf("\t3 出栈\n");printf("\t4 是否为空栈\n");printf("\t5 退出\n");}void init(LinkStack &L, LinkStack &R){L = (LinkStack)malloc(sizeof(StackNode));L->next = L->pre =  NULL;R = L;}void push(LinkStack &L, LinkStack &R, int x){ LinkStack nx = (LinkStack)malloc(sizeof(StackNode)); nx->data = x; nx->next = NULL; nx->pre = R; R->next = nx; R = nx;}bool Stack_pop(LinkStack &L, LinkStack &R){    if(L == R) return false;    LinkStack p = R->pre;    free(R);    R = p;    R->next = NULL;    return true;}void display(LinkStack L, LinkStack R){    if(L == R)    {        puts("Empty!");        return ;    }printf("base ----> top\n");L = L->next;while(L)    {        printf("%d ", L->data);        L = L->next;    }    printf("\n");}void is_Empty(LinkStack L, LinkStack R){    if(L == R) puts("Yes");    else puts("No");}int main(){LinkStack L, R;int num, now;while(1){menu();scanf("%d", &num);switch(num){case 1 : init(L, R); break;case 2 : printf("Input\n"); scanf("%d",&now); push(L, R, now); display(L, R); break;            case 3 :            if(Stack_pop(L, R))            {                printf("after delete\n");                display(L, R);            }            else printf("Empty!\n");            break;            case 4: is_Empty(L, R);}if(num == 5) break;}return 0;}