题解 | #由两个栈组成的队列#

由两个栈组成的队列

http://www.nowcoder.com/practice/6bc058b32ee54a5fa18c62f29bae9863

package main
import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	numofAction := 0
	l := &stacklist{[]int{}, []int{}}
	fmt.Scanln(&numofAction)
	sc := bufio.NewScanner(os.Stdin)
	action, num := "", 0
	for i := 0; i < numofAction; i++ {
		sc.Scan()
		orderString := strings.Split(sc.Text()," ")
		action = orderString[0]
		switch action {
		case "add":
			num,_ = strconv.Atoi(orderString[1])
			l.add(num)
		case "poll":
			l.pop()
		case "peek":
            fmt.Println(l.peek())
		}

	}
}

type stacklist struct {
	stack1 []int
	stack2 []int
}

func (s *stacklist) add(i int) {
	s.stack1 = append(s.stack1, i)
}
func (s *stacklist) pop() {
	if len(s.stack2) == 0 {
		s.stack2 = append(s.stack2, s.stack1...)
		s.stack1 = []int{}
		s.stack2 = s.stack2[1:]
	} else {
		s.stack2 = s.stack2[1:]
	}
}
func (s *stacklist) peek() int {
	if len(s.stack2) == 0 {
		s.stack2 = append(s.stack2, s.stack1...)
		s.stack1 = []int{}
		i := s.stack2[0]
		return i
	} else {
		i := s.stack2[0]
		return i
	}
}

全部评论

相关推荐

面试摇了我吧:啊哈哈面试提前五个小时发,点击不能参加就是放弃
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务