数据结构栈基本操作

本章内容:顺序栈、链栈的结构定义、初始化、判空、进栈、入栈、测试的主函数。

顺序栈:

#include <stdio.h>
#include <stdlib.h>
#define maxsize 100
//顺序栈定义
typedef struct
{
    int data[maxsize];
    int top;
}Stack;
//初始化栈
void initStack(Stack &S)
{
    S.top=-1;
}
//判断栈为空
int isEmpty(Stack S)
{
    if(S.top==-1)
        return 1;
    else
        return -1;
}
//进栈代码
int push(Stack &S,int x)
{
    if(S.top==maxsize-1)
        return -1;
    S.top++;
    S.data[S.top]=x;
    return 1;
}
//出栈代码,出栈数据存于x内
int pop(Stack &S,int &x)
{
    if(S.top==-1)
        return -1;
    x=S.data[S.top];
    S.top--;
    return -1;
}
int main()
{
    int n;
    int x;
    Stack S;
    initStack(S);
    n=isEmpty(S);
    printf("%d\n",n);
    push(S, 8);
    pop(S, x);
    printf("%d\n",x);
    n=isEmpty(S);
    printf("%d\n",n);
    return 0;
}

链栈:

#include <stdio.h>
#include <stdlib.h>
#define maxsize 100
typedef struct StackNode
{
    int data;
    struct StackNode *next;
}StackNode,*SNode;
void initStack(SNode &S)
{
    S=(SNode)malloc(sizeof(StackNode));
    S->next=NULL;
}
int isEmpty(SNode S)
{
    if(S->next==NULL)
        return 1;
    return -1;
}
//进栈
void push(SNode &S,int x)
{
    SNode q;
    q=(SNode)malloc(sizeof(StackNode));
    q->next=NULL;
    //头插法插入节点
    q->data=x;
    q->next=S->next;
    S->next=q;
}
//出栈
int pop(SNode &S,int &x)
{
    //判断是否为空
    if(S->next==NULL)
        return -1;
    //虽然不用q也可以进行链接,但是出栈节点就会丢失,无法释放掉。
    SNode q;
    q=S->next;
    x=q->data;
    S->next=q->next;
    free(q);
    return x;
}
int main()
{
    SNode S;
    int x,n;
    initStack(S);
    n=isEmpty(S);
    printf("%d\n",n);
    push(S, 3);
    push(S, 7);
    push(S, 9);
    push(S, 5);
    printf("%d\n",pop(S,x));
    printf("%d\n",pop(S,x));
    printf("%d\n",pop(S,x));
    printf("%d\n",pop(S,x));
    //输出空栈
    printf("%d\n",pop(S,x));
    return 0;
}

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值