顺序栈的基本操作

顺序栈的基本操作

1、定义:

  • ​ 作为一种限定性线性表,是将线性表的插入和删除运算限制为仅在表的一端进行。(先进后出)

2、栈的存储结构。

  1. 顺序栈:用顺序储存结构实现的栈。是利用一组地址连续的储存单元依次存放自栈底到栈顶的数据元素,同时由于栈的操作的特殊性,还必须附设一个位置的指针top来动态的指示栈顶元素在顺序栈中的位置。

3、结构示意图

在这里插入图片描述

4、*&解释

&是C++中的引用,可以直接改变原地址中的值。
*表示指针,表示地址传递

5、基本操作实现

#include<stdio.h>
#include<stdbool.h>					//bool(布尔类型的头文件)
#include<string.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef int ElementType;
/**
 * 顺序栈
 */
typedef struct SeqStack
{
    ElementType top;           //栈顶
    ElementType elem[MAXSIZE]; //一维数组
    // int stackSize;
} SeqStack;
//初始化
void InitStack(SeqStack *&s)
{
	 s = (SeqStack *)malloc(sizeof(SeqStack));
    s->top = -1;
}
//销毁栈
void DestoryStack(SeqStack *&s)
{
	free(s);
}
//判空操作
bool IsEmpty(SeqStack *s)
{
	return (s->top == -1);
}
//压栈
bool Push(SeqStack *&s,ElementType e)
{
	if (s->top ==(MAXSIZE-1))
	{
		return false;
	}
	s->top++;
	s->elem[s->top] = e;
	return true;
}
//弹栈
bool Pop(SeqStack *&s , ElementType &e)
{
	if (s->top == -1)
	{
		return false;
	}
	e = s->elem[s->top];
	s->top--;
	return true;
}
//得到栈顶的元素,不改变原栈
bool GetTop(SeqStack *s ,ElementType &e)
{
	if (s->top == -1)
	{
		return false;
	}
	e = s->elem[s->top];
	return true;
}
//进制转换方法.十进制转换为二进制。
void conversion(int n)
{
    SeqStack*s ;
    InitStack(s);
    int x;
    while (n)
    {
        Push(s,n%2);
        n = n/2;
    }
    while (!IsEmpty(s))
    {
       Pop(s,x);
       printf("%d",x);
    }
}
//主函数
int main()
{
	SeqStack *s ;
	InitStack(s);
	char x ;
	Push(s,'A');
	Push(s,'B');
	Push(s,'C');
	Pop(s,x);
	printf("%c",x);
    Push(s,'D');
    Pop(s,x);
	printf("%c",x);
	Pop(s,x);
	printf("%c",x);
	Pop(s,x);
	printf("%c",x);
	conversion(67);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值