栈与队列
栈:
- 先进后出
- api:
pushpoplength
队列:
- 先进先出
- api:
adddeletelength
栈与数组有什么区别?
栈是一种逻辑结构,理论模型,不管如何实现不受编程语言限制。
数组是一种物理结构,真实功能实现,有特定api,受编程语言限制。
队列与数组有什么区别?
队列可以用两个栈来实现,队列同样是一种逻辑结构。
具体体现
有效的括号
这是一道经典用栈来匹配有效括号的题。
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const left = []
const right = []
const len = s.length
for(let i = 0; i < len; i++) {
let curStr = s.charAt(i)
// 遇到左括号就入栈left
if(curStr === '(' || curStr === '[' || curStr === '{') {
left.push(curStr)
} else {
// 遇到右括号对应的左括号是否 === left栈顶
const leftTop = left.pop()
if(isRight(curStr) !== leftTop) {
return false
}
}
}
return !left.length
};
function isRight(s) {
const obj = {
')': '(',
']': '[',
'}': '{'
}
return obj[s]
}
队列——数组实现
class Queue {
private stack1: number[] = []
private stack2: number[] = []
add(n: number) {
this.stack1.push(n)
}
delete(n: number) {
const stack1 = this.stack1
const stack2 = this.stack2
// 把stack1的数都给到stack2
while (stack1.length) {
const top = stack1.pop()
if (top) {
stack2.push(top)
}
}
// 出队列
stack2.pop
// 出完队之后,把数都“还给”stack1
while (stack2.length) {
const top = stack2.pop()
if (top) {
stack1.push(top)
}
}
}
get length(): number {
return this.stack1.length
}
}
队列——链表实现
interface LinkListNode {
value: number
next: LinkListNode | null
}
class Queue {
private head: LinkListNode = null
private tail: LinkListNode = null
private len = 0
add(value: number): void {
const newNode: LinkListNode = {
value,
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
this.head = headNode.next
const value = headNode.value
this.len--
return value
}
get length(): number {
return this.len
}
}
选择对的数据结构比算法优化更重要!!