go语言实现栈和队列

go语言实现栈和队列

2021年4月6日
22:42

go语言实现栈和队列主要用到append切片(用内置数组类型进行操作)
设数组var s []int
入栈:s=append(s,x) //x为添加的数据的类型
出栈:s=s[:len(s)-1]

设数组var q []int
入队:q=append(q,x)
出队:q=q[1:]

 


例题1.---------20. 有效的括号

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
 

示例 1:

输入:s = "()"
输出:true
示例 2:

输入:s = "()[]{}"
输出:true
示例 3:

输入:s = "(]"
输出:false
示例 4:

输入:s = "([)]"
输出:false
示例 5:

输入:s = "{[]}"
输出:true
 

提示:

1 <= s.length <= 104
s 仅由括号 '()[]{}' 组成

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

func isValid(s string)bool{
    //奇数个字符一定不满足题设
    n:=len(s)
    if n%2==1{
        return false
    }
    pairs:=map[byte]byte{
        ')':'(',
        ']':'[',
        '}':'{',
    
    }
    stack:=[]byte{}
    //循环遍历每个字符
    for i:=0;i<n;i++{
        //判断是左括号还是右括号,
        //是右括号,取map中对应左括号
        if pairs[s[i]]>0{
            //检查是否栈顶元素(左括号)与当前符号(右括号)匹配,检查栈是否为空
            if len(stack)==0||stack[len(stack)-1]!=pairs[s[i]]{
            return false
            }
            //出栈
            stack=stack[:len(stack)-1]
        }else{
        //是左括号则入栈
            stack=append(stack,s[i])
        }
        
    }
    if len(stack)==0{
        return true
    }else{
        return false
    }
    
}

  


 

 225. 用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。

实现 MyStack 类:

void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
 

注意:

你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
 

示例:

输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
 

提示:

1 <= x <= 9
最多调用100 次 push、pop、top 和 empty
每次调用 pop 和 top 都保证栈不为空
 

进阶:你能否实现每种操作的均摊时间复杂度为 O(1) 的栈?换句话说,执行 n 个操作的总时间复杂度 O(n) ,尽管其中某个操作可能需要比其他操作更长的时间。你可以使用两个以上的队列。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-stack-using-queues
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

//双队列做法,主队列q1存放的是栈内元素,q1出队相当于出栈
//每次push加入新数至辅助队列q2,主队列存放之前栈内元素依次加入辅助队列,再交换主队列和辅助队列(实现了主队列q1一直保存的是栈内元素)
type MyStack struct {
    q1 []int
    q2 []int
}

/** Initialize your data structure here. */
func Constructor() (s MyStack) {
    return
}

/** Push element x onto stack. */
func (s *MyStack) Push(x int)  {
    //入辅助队列q2
    s.q2=append(s.q2,x)
    //如果主队列不为空
    for len(s.q1)>0{
        //将主队列q1中元素依次出队,再入队到辅助队列q2
        s.q2=append(s.q2,s.q1[0])
        s.q1=s.q1[1:]
    }
    //交换两个队列
    s.q1,s.q2=s.q2,s.q1
}

/** Removes the element on top of the stack and returns that element. */
func (s *MyStack) Pop() int {
    //只用将主队列出队即可实现出栈操作
    v:=s.q1[0]
    s.q1=s.q1[1:]
    return v
}

/** Get the top element. */
func (s *MyStack) Top() int {
    return s.q1[0]
}

/** Returns whether the stack is empty. */
func (s *MyStack) Empty() bool {
    if len(s.q1)==0{
        return true
    }else{
        return false
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Top();
 * param_4 := obj.Empty();
 */

  

posted @ 2021-04-21 10:19  秋月桐  阅读(1197)  评论(1编辑  收藏  举报