C语言用栈反转字符串,字符反转的问题C语言

题意:

输入一行字符串,将每一个单词(只有空格隔开)倒序输出!

注意:

开始和结尾可能有多个空格,单词之间可能有多个空格!

Sample Input

3

olleh !dlrow

m’I morf .udh

I ekil .mca

Sample Output

hello world!

I’m from hdu.

I like acm.

我下面的代码跑的时候开始和结尾的空格都是按原空格输出的啊。可为什么还是Presentation Error,望指教问题出在哪里。谢谢!

bVNN1L?w=193&h=185

#include

#include

#define MAXSIZE 1001

typedef char ElementType;

typedef struct Node *PtrToNode;

typedef PtrToNode Stack;

typedef struct Node

{

ElementType Data;

PtrToNode Next;

};

Stack CreateStack();

int IsEmpty( Stack S );

void Push(ElementType X, Stack S);

void Pop(Stack S);

void MakeEmpty(Stack S);

void DisplayStack(Stack S);

int main() {

char string[MAXSIZE], warp;

char *PtrToChar;

int instance;

Stack S;

scanf("%d",&instance);

warp = getchar();

S = CreateStack();

if( warp == '\n')

{

while( instance-- ) {

gets(string);

PtrToChar = string;

while( *PtrToChar != '\0' ){

if( *PtrToChar != ' ' )

{

Push( *PtrToChar,S );

}

else

{

DisplayStack(S);

printf("%c",*PtrToChar);

MakeEmpty(S);

}

PtrToChar++;

}

if( !IsEmpty(S))

{

DisplayStack(S);

MakeEmpty(S);

}

puts("\n");

}

}

return 0;

}

Stack CreateStack( )

{

Stack S;

S = malloc( sizeof( struct Node) );

if(S == NULL)

exit(0);

S->Next = NULL;

return S;

}

int IsEmpty( Stack S )

{

return S->Next == NULL;

}

void Push(ElementType X, Stack S)

{

PtrToNode TmpCell;

TmpCell = malloc(sizeof( struct Node));

if(TmpCell == NULL)

exit(0);

else

{

TmpCell->Data = X;

TmpCell->Next = S->Next;

S->Next = TmpCell;

}

}

void Pop( Stack S)

{

PtrToNode firstCell;

if(S == NULL)

exit(0);

if( S->Next == NULL)

{

printf("Empty Stack");

exit(0);

}

else

{

firstCell = S->Next;

S->Next = S->Next->Next;

free(firstCell);

}

}

void DisplayStack( Stack S)

{

if( S == NULL )

exit(0);

else

{

/*栈顶指针,不含元素,要特殊处理一下*/

S = S->Next;

while( S != NULL){

printf("%c",S->Data);

S = S->Next;

}

}

}

void MakeEmpty( Stack S)

{

if(S == NULL)

exit(0);

else

while( !IsEmpty( S ) )

Pop( S );

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值