HDU-1062,Text Reverse(字符串处理 and 栈)

简介: HDU-1062,Text Reverse(字符串处理 and 栈)

Problem Description:


Ignatius likes to write words in reverse way. Given a single line of text which is written by Ignatius, you should reverse all the words and then output them.


Input:


The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.

Each test case contains a single line with several words. There will be at most 1000 characters in a line.  


Output:


For each test case, you should output the text which is processed.


Sample Input:

3


olleh !dlrow


m'I morf .udh


I ekil .mca  


Sample Output:


hello world!

I'm from hdu.

I like acm.


解题思路:


看到题目,相信大家应该知道这道题就是字符串逆置,我们可以考虑将其存入栈中,然后依次输出就可以了,题目的要求是完全符合栈的“先进后出,后进先出”的特点的。剩下的我们看代码↓↓↓


程序代码:


#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
int main()
{
  int n;
  char ch;
  scanf("%d",&n);
  getchar();//吸收回车符 
  while(n--)
  {
    stack<char> s;//定义一个栈 
    while(1)
    {
      ch=getchar();//每次读入一个字符 
      if(ch==' '||ch=='\n'||ch==EOF)//三个特殊的字符 
      {
        while(!s.empty())//栈不为空 
        {
          printf("%c",s.top());//输出此时的栈顶元素 
          s.pop();//清除栈顶元素 
        }
        if(ch=='\n'||ch==EOF)//结束条件 
          break;
        printf(" ");//记得每个单词(除了最后一个)后面都有一个空格 
      }
      else
        s.push(ch);//将这个字符压入栈 
    }
    printf("\n");
  }
  return 0;
}


相关文章
|
5天前
|
算法 C语言
【数据结构与算法 经典例题】使用栈实现队列(图文详解)
【数据结构与算法 经典例题】使用栈实现队列(图文详解)
|
5天前
|
存储 测试技术
【数据结构】操作受限的线性表,栈的具体实现
【数据结构】操作受限的线性表,栈的具体实现
17 5
|
5天前
|
算法 C语言
【数据结构与算法 经典例题】使用队列实现栈(图文详解)
【数据结构与算法 经典例题】使用队列实现栈(图文详解)
|
6天前
|
算法
【C/数据结构和算法】:栈和队列
【C/数据结构和算法】:栈和队列
15 1
|
10天前
|
C++
【洛谷 P1044】[NOIP2003 普及组] 栈 题解(递归+记忆化搜索)
**NOIP2003普及组栈问题**:给定操作数序列1到n,仅允许push(进栈)和pop(出栈)操作。目标是计算所有可能的输出序列总数。输入包含一个整数n(1≤n≤18)。示例输入3,输出5。当队列空时返回1,栈空则只能入栈,栈非空时可入栈或出栈。AC C++代码利用记忆化搜索求解。
9 1
|
12天前
|
算法
$停车场管理系统 栈与队列
$停车场管理系统 栈与队列
9 1
|
2天前
|
存储 算法 调度
算法与数据结构-栈篇
算法与数据结构-栈篇
11 0
|
3天前
|
存储 人工智能 程序员
技术心得记录:堆(heap)与栈(stack)的区别
技术心得记录:堆(heap)与栈(stack)的区别
|
5天前
【海贼王的数据航海】栈和队列
【海贼王的数据航海】栈和队列
5 0
|
5天前
|
存储 算法 编译器
【数据结构与算法】使用数组实现栈:原理、步骤与应用
【数据结构与算法】使用数组实现栈:原理、步骤与应用