本文介绍了一种栈的数据结构实现——顺序存储,并通过具体的C语言代码实现了栈的基本操作,如初始化、进栈、出栈及打印栈内元素等。此外,还提供了一个基于栈的进制转换功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//栈的顺序存储
//stack.h

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

#define MAXSIZE 20
typedef int ElemType;

typedef struct //SqStack
{ElemType a[MAXSIZE];
int top;
}SqStack;

void init_s(SqStack *s)
{
	s=(SqStack *)malloc(sizeof(SqStack));
	s->top=-1;
}

/******************************检测完毕*****************************/
void out_s(SqStack *s)//print the elems of the stack
{
	int i;
	if(s->top==-1) printf("\n Stack is NULL");
	else{ i=s->top;
	while(i!=-1) 
	{printf("\n data[%d]=%d", i,s->a[i]);i--;}
	}
}

/****************************检测完毕*******************************/
void push(SqStack *s,ElemType e)
{
	if(s->top==MAXSIZE-1)printf("\n Stack is overflow!");
	else{s->top++;
	s->a[s->top]=e;
	}
}

/*********************检测完毕**************************************/
ElemType pop(SqStack *s)
{
	ElemType x;
	if(s->top==-1) {printf("\n Stack is NULL");x=-1;}
	else{x=s->a[s->top];s->top--;}
	return x;
}


测试程序main

#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
#define MAXSIZE 20
typedef int ElemType;

SqStack s1,s2;
void conversion(int M,int N);
void main()
{
	int k,a,b;ElemType x,y;char ch;
	init_s(&s2);

	do{
		printf("\t\t============================\n");
		printf("\t\t==1、进栈                 ==\n");
		printf("\t\t==2、出栈                 ==\n");
		printf("\t\t==3、输出栈               ==\n");
		printf("\t\t==4、进制转换             ==\n");
		printf("\t\t==5、结束                 ==\n");
		printf("\t\t============================\n");
		scanf("%d",&k);
		switch(k)
		{
		case 1:{//ElemType y;
			printf("输入进栈元素:");
			scanf("%d",&y);
			push(&s2,y);
			printf("进栈元素是:%d\n",y);
			break;
			   }
		case 2:{x=pop(&s2);
			printf("出栈元素是:%d\n",x);
			break;
			   }
		case 3:{out_s(&s2);
			printf("\n");
			break;
			   }
		case 4:{printf("要进行进制转换的数是:");scanf("%d",&a);
			printf("转换成n进制,n=");scanf("%d",&b);
			conversion(a,b);
			break;
			   }
		}
		//printf("\n\n\t\t==按任意键返回主菜单==\n\t\t");
		//fflush(stdin);
		//scanf("%c",&ch);
	}while(k!=5);
}

void conversion(int M,int N)
{
	ElemType c;
	init_s(&s1);
	while(M!=0)
	{
		push(&s1,M%N);
		M=M/N;
	}
	printf("\n转换后的数字是:");
	while(s1.top!=0)
	{
		c=pop(&s1);
		printf("%d",c);
		//out_s(&s1);
	}
	printf("\n");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值