您的位置:首页 > 编程语言

栈代码

2016-04-26 11:10 190 查看
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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: