字符反转的问题C语言

查看:86
本文介绍了字符反转的问题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,望指教问题出在哪里。谢谢!

#include <stdio.h>
#include <stdlib.h>
#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 );
}

解决方案

puts("\n") 改成 printf("\n")

这篇关于字符反转的问题C语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆