堆栈的学习代码实现

  • 顺序存储结构
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#define  STACK_INIT_SIZE  5
#define ok 1
#define error 0
using namespace std;
typedef int elemtype;
typedef int status;
typedef struct
{
    elemtype *base;
    elemtype *top;
    int stacksize;
}sqstack;
status initstack(sqstack &s)
{
    s.base=(elemtype*)malloc(STACK_INIT_SIZE*sizeof(elemtype));
    if(!s.base)
        exit(0);
    s.top=s.base;//base 相当于数组名,首地址
    s.stacksize=STACK_INIT_SIZE;
    return ok;
}
//销毁三步走:栈顶为空,栈的大小为0,释放空间
status destorystack(sqstack &s)
{
    s.top=NULL;
    s.stacksize=0;
    free(s.base);
    return ok;
}
status clearstack(sqstack &s)
{
    s.top=s.base;
    return ok;
}
//对栈进行操作时要注意栈是否为空,即s.base=s,top;
status push(sqstack &s,elemtype e)
{
    if(s.top-s.base==5)//base相当于数组名,数组名这一指针加一代表地址挪一个int;
        cout<<"No";
    *s.top=e;
    s.top++;
    return ok;
}
status pop(sqstack &s, elemtype e)
{
    if(s.top=s.base)
        return error;
    else
        {
            s.top--;
            e=*s.top;
            return e;
        }
}
int main()
{
    sqstack s;
    printf("构造一个空栈……\n");
    initstack(s);
    int i,n ;
    printf("输入栈的长度:\n");
    scanf("%d",&n);
    for (i = 1; i <= n; i++)
    {
        printf("输入栈的第%d个元素\n",i);
        ++s.top;
        scanf("%d",s.top-1);
    }
    push(s,3);

}

  • 链式存储结构
#include<iostream>
#include<stdio.h>
#include<malloc.h>
typedef int elementtype;
using namespace std;
typedef struct snode *stack;
struct snode
{
    elementtype data;
    stack next;
};
//初始化堆栈,返回的是堆栈的一个指针
stack createstack()
{
    stack s;
    s=(stack)malloc(sizeof(stack));//开辟空间时用指针stack。和用数据类型struct snode相同
    s->next=NULL;
    return s;
}
int isempty(stack s)
{
    return (s->next == NULL);
}
//只能选取链表头作为top,这样实现pop和push如下所示
//如果选取链表为,删除时无法令上个元素做top(单向链表不可往回)
void push(stack s,elementtype e)
{
    stack tmp;
    tmp=(stack)malloc(sizeof(stack));
    tmp->data=e;
    tmp->next=s->next;
    s->next=tmp;
}
elementtype pop(stack s)
{
    stack first;//再新命名一个堆栈,便于与topnext区分;
    elementtype number;
    if(isempty(s))//不是只有isempty
        return 0;
    else
    {
        first=s->next;
        number=first->data;
        s->next=first->next;
        free(first);
        return number;
    }
}
int main(){
    stack s;
    s=createstack();
    push(s,2);
    push(s,4);
    push(s,9);
    push(s,666);
    cout<<pop(s);
	return 0;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值