用栈实现反转字符串输入问题

给定一个字符串,逐个翻转字符串中的每个单词。例如,输入: "the sky is blue",输出: "blue is sky the"。

 

package main

import (
    "fmt"
    "strings"
)

type SStack struct {
    elems []string
}

func (this SStack) Is_empty() bool {
    return len(this.elems) == 0
}

func (this SStack) Top() string {
    if this.Is_empty() {
        panic("in SStack.top")
    }
    return this.elems[len(this.elems)-1]
}

func (this *SStack) Push(elem string) {
    this.elems = append(this.elems, elem)
}

func (this *SStack) Pop() string {
    if this.Is_empty() {
        panic("in SStack.pop")
    }
    elem := this.elems[len(this.elems)-1]
    this.elems = this.elems[:len(this.elems)-1]
    return elem
}

func main() {
    s := SStack{}
    str := "the sky is blue"
    ss := strings.Split(str, " ")

    for _, i := range ss {
        s.Push(i)
    }
    var resultStr string
    for !s.Is_empty() {
        resultStr += s.Pop()
        resultStr += " "
    }
    resultStr = strings.TrimSpace(resultStr)
    fmt.Println(resultStr)
}

 

posted @ 2020-08-31 17:05  顽强的allin  阅读(339)  评论(0编辑  收藏  举报