利用栈来实现对字符串的逆置

//思路:将字符串数组进行入栈操作,然后通过出栈的方式进行逆置(栈的先进后出的性质)

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
//定义一个顺序栈 
typedef struct Node{
	char str[MAXSIZE];
	int top;
}SeqStack;
//初始化 
void InitStack(SeqStack &S) {
	S.top=-1;
}
//判断顺序栈是否为空 
int StackEmpty(SeqStack &S)
{
	if(S.top==-1)
		return true;
	else
		return false;
		
}
//入栈 
int Push(SeqStack &S,char x)
{
	if(S.top==MAXSIZE-1)
	return false;
	else
	{
		S.top++;
		S.str[S.top]=x;
		return true;
		
	}
}
//出栈 (在这里我们将栈顶元素的值存在x中,并将这个值返回) 
char Pop(SeqStack &S)
{
	char x;
	if(S.top==-1)
		printf("栈空");
	else
	{
		x=S.str[S.top];
		S.top--;
		return x;
	}
}
int main(){
    char str[MAXSIZE];
    SeqStack S;
    int i;
    printf("逆置前的字符串为:  \n");
    gets(str);//输入一个字符串 
    InitStack(S);
    for (i=0;str[i]; i++)
	{
        Push(S, str[i]);//将字符数组中元素入栈 
    }
    printf("逆置后的字符串为: \n");
    while (!StackEmpty(S))
	{
        putchar(Pop(S));//输出调用Pop函数返回的栈顶元素(存在x中) 
    }
    printf("\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值