c语言反转函数1001无标题,字符反转的问题C语言

该博客主要讨论一个C语言程序,其目的是读取一行字符串,并将每个单词进行倒序输出,同时保留原始的空格。博主在实现过程中遇到了空格处理的问题,即代码在处理开始和结尾的空格时未能按照预期工作,导致PresentationError。代码中使用了栈数据结构来辅助单词反转,但未完全解决空格问题。博客内容涉及字符串处理、栈操作和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 );

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值