栈代码

1. 栈以顺序存储方式实现

(1)入栈:栈满 top==Maxsize-1

(2)出栈: 栈空top==-1;

#include<stdio.h>

#include<malloc.h>
#include<iostream>
typedef struct stock
{
    int Maxsize;
    int top;
    int *ps;
}Stock;

// 初始化栈
void InitStock(stock *s, int ms)
{
    s->Maxsize = ms;
    s->top = -1;
    s->ps =(int*)malloc(ms*sizeof(int));
}

//出栈操作
int pop(stock*s)
{
    if (s->top != -1)
    {
      return s->ps[s->top --];
    }
}
// 入栈操作

void push(stock*s, int val)
{
    if (s->top == s->Maxsize - 1)
    {
        printf("栈已满,%d不可入栈,正在处理,请稍等。",val);
        getchar();
        printf("%d已出栈,%d可入栈",pop(s), val);
        getchar();
    }
    s->ps[++s->top] = val;
    printf("%d已入栈", val);
    getchar();
}
//释放栈空间
void freestock(stock*s)
{
    s->Maxsize = 0;
    free(s->ps);
    s->ps = NULL;
}

void main()
{
    Stock s; int i, ms;
    int a[7] = { 10,11,12,13,14,15,16 };
    printf("请输入栈的最大元素个数:\n");
    std::cin>>ms;
    InitStock(&s, ms);
    for (i = 0; i < ms; i++)
    {
        push(&s,a[i] );
    }
    while (s.top != -1)
    {
        printf("%d已出栈\n", pop(&s));
        getchar();
    }
    freestock(&s);

}


2. 栈以链式存储方式实现

#include<stdio.h>
#include<malloc.h>
#define NULL 0
typedef struct student
{
    int data;
    struct student *next;
}node;

typedef struct queuestack
{
    node *zhandi, *top;
}queue;

queue*push(queue *HQ, int x)
{
    node*s;
    s = (node*)malloc(sizeof(node));
    s->data = x;
    s->next = NULL;
    if (HQ->zhandi == NULL)
    {
        HQ->zhandi = s;
        HQ->top = s;
    }
    else
    {
        HQ->top->next = s;
        HQ->top = s;
    }
    return HQ;
}

queue*pop(queue*HQ)
{
    node*p; int x;
    if (HQ->zhandi == NULL)
        printf("\nyichu");
    else
    {
        x = HQ->zhandi->data;
        p = HQ->zhandi;
        if (HQ->zhandi == HQ->top)
        {
            HQ->zhandi = NULL;
            HQ->top = NULL;
        }
        else
        {
            while (p->next != HQ->top)
            {
                p = p->next;

            }
            HQ->top = p;
            HQ->top->next = NULL;
        }
    
    }
    return (HQ);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值