// Push push a new node into the stack(on the top) func(stack *Stack)Push(val interface{})error { stack.lock.Lock() defer stack.lock.Unlock() pNode := new(node) pNode.val = val pNode.prev = stack.top stack.top = pNode stack.length++ returnnil }
// Pop pop the top node of the stack func(stack *Stack)Pop()(ok bool, err error) { stack.lock.Lock() defer stack.lock.Unlock() if stack.top == nil { err = fmt.Errorf("pop a empty stack") return } stack.top = stack.top.prev stack.length-- ok = true return }
funclongestWPI(hours []int)int { var arr []int = make([]int, len(hours)) var prefixSum []int = make([]int, len(hours)+1) tmp := 0 for i, val := range hours { if val > 8 { arr[i] = 1 } else { arr[i] = -1 } } prefixSum[0] = 0 for i := 0; i < len(arr); i++ { tmp += arr[i] prefixSum[i+1] = tmp } res := 0 for i := 0; i < len(prefixSum); i++{ // 实在没有理解最后的优化思路,太复杂了 for j := i+1; j < len(prefixSum); j++{ if prefixSum[j] > prefixSum[i] { if j - i > res { res = j - i } } } } return res }
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcpostorderTraversal(root *TreeNode) []int { var stack []*TreeNode var res []int var left *TreeNode var right *TreeNode var top *TreeNode if root == nil { // 注意边界情况检查!!!! return res } stack = append(stack, root) forlen(stack) > 0 { top = stack[len(stack)-1] res = append(res, top.Val) left = top.Left right = top.Right stack = stack[:len(stack)-1] if left != nil { stack = append(stack, left) } if right != nil { stack = append(stack, right) } } for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 { res[i], res[j] = res[j], res[i] } return res