栈的基本操作(数组/链表)

来源:互联网 发布:2017年复杂网络大会 编辑:程序博客网 时间:2024/05/16 13:03

下面是分别用数组和链表演示栈的一些操作:


数组实现顺序栈:

#include<stdio.h>#define deep 6int Stack[deep];int top=-1;void Push(int value);int Pop();void show();int main(){    Push(1);    Push(3);    Push(5);    Push(7);    show();    printf("弹出的元素:%d\n",Pop());    printf("弹出的元素:%d\n",Pop());    show();    return 0;}void Push(int value){    if(top==deep-1)    {        printf("栈已满");        exit(-1);    }    top++;    Stack[top]=value;}int Pop(){    if(top==-1)    {        printf("栈已空");        exit(-1);    }    return Stack[top--];}void show(){    printf("栈:");    for(int i=0; i<=top; i++)        printf("%d\t",Stack[i]);    printf("\n");}

链表实现链栈:

#include<stdio.h>#include<stdlib.h>typedef struct Stack{    int data;    struct Stack *next;} Node,*pnode;pnode stack=NULL;void push(int value);int pop();void show();int main(){    push(1);    push(3);    push(5);    push(7);    show();    printf("出栈元素:%d\n",pop());    printf("出栈元素:%d\n",pop());    show();    return 0;}void push(int value) //链栈容量不需要判断{    pnode newnode=(pnode)malloc(sizeof(Node));    newnode->data=value;    newnode->next=stack;    stack=newnode;}int pop(){    if(stack!=NULL)    {        pnode temp=stack;        stack=stack->next;        int temps=temp->data;        free(temp);        return temps;    }    else    {        printf("空栈");        return -1;    }}void show(){    pnode node=stack;    printf("栈顺序:\t");    while(node!=NULL)    {        printf("%d\t",node->data);        node=node->next;    }    printf("\n");}