1、括号匹配
https://leetcode.cn/problems/valid-parenthese
/*** 括号匹配*/function isMatch(left, right) {if (left === '(' && right === ')') return trueif (left === '{' && right === '}') return trueif (left === '[' && right === ']') return truereturn false}function matchBraket(str) {const len = str.lengthif (len === 0) return trueconst leftSymbol = '({['const rightSymbol = ']})'const stack = []for (let i = 0; i < len; i++) {const s = str[i]if (leftSymbol.includes(s)) {// 包含左括号,进栈stack.push(s)} else if (rightSymbol.includes(s)) {// 包含右括号,拿出栈顶元素和当前元素匹配对比,如果为true则出栈const top = stack[stack.length - 1]if (isMatch(top, s)) {stack.pop()}}}return stack.length === 0}console.log(matchBraket("{[()]}"))
2、两个栈实现一个队列
https://leetcode.cn/problems/implement-queue-using-stacks/
class MyQueue {constructor() {this.stack1 = []this.stack2 = []}/*** 入队*/add(n) {this.stack1.push(n)}/*** 出队*/delete() {// 1、讲stack1中的所有数据移动到stack中while (this.stack1.length) {const n = this.stack1.pop()if (n) {this.stack2.push(n)}}// 2、stack2.popconst res = this.stack2.pop()return res}length() {return this.stack2.length}}const res = new MyQueue()res.add(1)res.add(2)res.add(3)console.log(res.delete())console.log(res.delete())
3、反转单向链表
/*** 创建链表* @param {*} arr* @returns*/function createLinkList(arr) {const len = arr.lengthif (!len) throw new Error('arr is empty')let curNode = {value: arr[len - 1]}if (len === 1) {return curNode}for (let i = len - 2; i >= 0; i--) {curNode = {value: arr[i],next: curNode}}return curNode}/*** 反转* @param {*} listNode*/function reverseLinkList(listNode) {// 定义指针let prevNode = undefinedlet curNode = undefinedlet nextNode = listNode// 以nextNode为主,遍历链表while (nextNode) {// 第一个元素,删掉next,防止循环引用if (curNode && !prevNode) {delete curNode.next}// 反转指针if (curNode && prevNode) {curNode.next = prevNode}// 整体向后移动指针prevNode = curNodecurNode = nextNodenextNode = nextNode?.next}// 当nextNode为空时,此时curNode尚未设置nextcurNode.next = prevNodereturn curNode}const arr = [100, 200, 300, 400, 500]const list = createLinkList(arr)console.log('list', list)const list1 = reverseLinkList(list)console.log('list1', list1)
