栈的顺序存储结构

一、栈的顺序存储结构:

代码如下;

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 3
typedef int Datatype;


typedef struct
{
	Datatype data[MAXSIZE];
	int top;
	
}Sqstack; 


void menu();
void Stack_Init(Sqstack *s);
void In_Stack(Sqstack *s,Datatype x);
int Out_Stack(Sqstack *s);


int main()
{
	int select;
	int x;
	Sqstack s;
	
	Stack_Init(&s);
	
	while(1)
	{
		menu();
		printf("请输入操作数:\n");
		scanf("%d",&select);
		switch(select)
		{
			case 1:printf("请输入入栈数据:\n");
					scanf("%d",&x);
					In_Stack(&s,x);
					break;
			case 2:printf("出栈的数据为:%d\n",Out_Stack(&s));break;
			case 3:break;
			case 0:exit(0);break;
			default:break;
		}	
		system("pause");
		system("cls");
	}
	
	return 0;	
} 


void menu()
{
	printf("(1)---请入栈!\n");
	printf("(2)---请出栈!\n");
	printf("(3)---输出栈中数据!\n");
	printf("(0)---退出!\n");
} 

void Stack_Init(Sqstack *s)
{
	s->top=-1;
}

void In_Stack(Sqstack *s,Datatype x)
{
	if(s->top>=MAXSIZE-1)
	{
		printf("栈已满!\n");
		
	}
	else
	{
		s->top=s->top+1;
		s->data[s->top]=x;
		printf("入栈成功!\n");
	}
	
}

int Out_Stack(Sqstack *s)
{
	int data;
	
	if(s->top==-1)
	{
		printf("栈空!\n");
		return 0;
	}
	else
	{
		data=s->data[s->top];
		s->top=s->top-1;
		printf("出栈成功!\n");	
		return data;
	}
	
}在这里插入代码片
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 C++ 实现顺序存储结构的代码示例: ```cpp #include <iostream> using namespace std; const int MAX_SIZE = 100; // 定义的最大容量 class Stack { private: int data[MAX_SIZE]; // 存储元素的数组 int top_index; // 顶元素的下标 public: Stack() { top_index = -1; } // 构造函数,初始化顶下标为-1 bool push(int value); bool pop(); int top(); bool empty(); bool full(); }; bool Stack::push(int value) { if (full()) { cout << "已满,无法插入元素!" << endl; return false; } else { top_index++; data[top_index] = value; return true; } } bool Stack::pop() { if (empty()) { cout << "已空,无法弹出元素!" << endl; return false; } else { top_index--; return true; } } int Stack::top() { if (empty()) { cout << "已空,无法获取顶元素!" << endl; return -1; } else { return data[top_index]; } } bool Stack::empty() { return top_index == -1; } bool Stack::full() { return top_index == MAX_SIZE - 1; } int main() { Stack s; // 创建一个对象 s.push(1); s.push(2); s.push(3); s.pop(); cout << s.top() << endl; return 0; } ``` 在上面的代码中,我们使用数组来存储中的元素,使用 top_index 变量记录顶元素的下标,根据 top_index 的值来判断是否为空或已满。push() 方法用来向中插入元素,pop() 方法用来弹出顶元素,top() 方法用来获取顶元素,empty() 方法用来判断是否为空,full() 方法用来判断是否已满。在 main() 函数中,我们创建了一个对象 s,然后对进行了一些操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值