用链表实现队列
- 声明 head 和 tail
- add 是入队,先把传入的数据包成一个节点,如果 head 为空,head 就为新节点,tail也是新节点,如果tail有值,newNode 赋给 tail.next,这样新入的排在链表末端
- delete 出队,取出 head的值,再把 this.head 指向 head.next
interface IListNode {
value: number
next: IListNode | null
}
export class Queue {
private head: IListNode | null = null
private tail: IListNode | null = null
private len = 0
add(n: number) {
const newNode: IListNode = {
value: n,
next: null,
}
if (this.head == null) {
this.head = newNode
}
const tailNode = this.tail
if (tailNode) {
tailNode.next = newNode
}
this.tail = newNode
this.len++
}
delete(): number | null {
const headNode = this.head
if (headNode == null) return null
if (this.len <= 0) return null
const value = headNode.value
this.head = headNode.next
this.len--
return value
}
get length(): number {
return this.len
}
}
两个栈实现一个队列
- 入队列直接 stack1.push(n)
- 出队列,stack1 的元素全挪到 stack2, 拿到 stack2.pop 的结果,再把 stack2 全挪到 stack1
class Queue {
private stack1: number[] = []
private stack2: number[] = []
add(n: number) {
this.stack1.push(n)
}
delete(): number | null {
let res
const stack1 = this.stack1
const stack2 = this.stack2
while(stack1.length) {
const n = stack1.pop()
if (n != null) {
stack2.push(n)
}
}
res = stack2.pop()
while(stack2.length) {
const n = stack2.pop()
if (n != null) {
stack1.push(n)
}
}
return res || null
}
get length(): number {
return this.stack1.length
}
}
判断字符串里的括号是否正确成对匹配
- 先声明左右的符号集
left = '{[('
right = '}])'
- 遍历字符串,如果字符属于左集就压栈
- 如果属于右集,先判断栈头部的(刚才压入的)与当前的字符是否成对,如果成对就出栈,如果不成对,证明不匹配
- 遍历过后,如果栈空了,表明都能正确成对匹配,如果不空表示不能正确配对。
function isMatch(left: string, right: string): boolean {
if (left === '{' && right === '}') return true
if (left === '[' && right === ']') return true
if (left === '(' && right === ')') return true
return false
}
function matchBracket(str: string): boolean {
const length = str.length
if (length === 0) return true
const stack = []
const left = '{[('
const right = '}])'
for (let i = 0; i < length; i++) {
const txt = str[i]
if (left.includes(s)) {
stack.push(s)
} else if (right.includes(txt)) {
const top = stack[stack.length - 1]
if (isMatch(top, txt)) {
stack.pop()
} else {
return false
}
}
}
return stack.length === 0
}