一起学习数据结构与算法:队列

312 阅读1分钟

// 队列
function Queen(...data) {
	Object.defineProperties(this, {
		// 数据
		data: {
			configurable: false,
			enumerable: true,
			writable: true,
			value: data
		},
		// 长度
		length: {
			configurable: false,
			enumerable: true,
			get() {
				return this.data && this.data.length || 0
			},
			set() {
				return console.warn(`property length is readonly`);
			}
		},
		// 队列尾
		tail: {
			configurable: false,
			enumerable: true,
			get() {
				return this.length
			},
			set() {
				return console.warn(`property tail is readonly`);
			}
		},
		// 队列首
		head: {
			configurable: false,
			enumerable: true,
			get() {
				return 0
			},
			set() {
				return console.warn(`property head is readonly`);
			}
		}
	})
}
// 入队列 returns <Array> this.data
Queen.prototype.push = function (...data) {
	while(data.length) {
		this.data.push(data.shift())
	}
	return this.data
}
// 出队列 returns 出队列的元素
Queen.prototype.pop = function () {
	return Array.prototype.shift.apply(this.data)
}
// 获取队列队尾元素 returns 队列队尾元素
Queen.prototype.tailElement = function () {
	return this.data[this.tail - 1]
}
// 获取队列队尾元素 returns 队列队首元素
Queen.prototype.headElement = function () {
	return this.data[this.head]
}
// 清空队列 returns <Array> []
Queen.prototype.clear = function () {
	this.data = []
	return []
}
// 是否为空队列,returns <boolean> [true | false]
Queen.prototype.isEmpty = function () {
	return !this.length
}

const queen = new Queen(1, 2, 3, 4)
console.log(queen.data, queen.length, queen.head, queen.tail, queen.isEmpty())
console.log(queen.push(5, 6, 7))
queen.head = 2
queen.tail = 2
queen.length = 3
console.log(queen.pop(), queen.data, queen.length, queen.head, queen.tail, queen.isEmpty())
console.log(queen.tailElement(), queen.data, queen.length, queen.head, queen.tail, queen.isEmpty())
console.log(queen.headElement(), queen.data, queen.length, queen.head, queen.tail, queen.isEmpty())
console.log(queen.clear(), queen.data, queen.length, queen.head, queen.tail, queen.isEmpty())

console.log(`--------------- Stack 两个队列实现栈 -----------------`)
// stack1原始栈,stack2为stack1的出栈顺序构成的栈
function Stack(...data) {
	this.queen1 = new Queen(...data)
    this.queen2 = new Queen()
}
Stack.prototype.push = function (...data) {
    // 推入的时候要判断哪个队列中有值,就推入那个队列中
    return this[`queen${this.queen1.isEmpty() ? '2' : '1'}`].push(...data)
}
Stack.prototype.pop = function () {
     // 弹出的时候判断哪个队列中有值,则先将该队列中的n-1个值弹出并存入另一个队列中,然后弹出最后一个值则为结果
    if(this.queen1.isEmpty() && this.queen2.isEmpty()) return null
    if(this.queen1.isEmpty()) {
        while(this.queen2.length === 1) {
            this.queen1.push(this.queen2.pop())
        }
        return this.queen2.pop()
    }
    while(this.queen1.length === 1) {
        this.queen2.push(this.queen1.pop())
     }
    return this.queen1.pop()
}
const stack = new Stack(1,2,3)
stack.push(4,5,6)
console.log(stack.pop())
console.log(stack.pop())
console.log(stack.pop())