彭雄飞 發表於 2021-1-14 13:26:00

JavaScript 算法 1_1 下压堆栈 (链表实现)

<h1 id="javascript-算法-1_1-下压堆栈-链表实现">JavaScript 算法 1_1 下压堆栈 (链表实现)</h1>
<blockquote>
<p>链表是一种递归的数据结构</p>
</blockquote>
<p></p><div class="toc"><div class="toc-container-header">目录</div><ul><li>JavaScript 算法 1_1 下压堆栈 (链表实现)<ul><li>1. 节点结构</li><li>2. 构造链表</li><li>3. 从表头插入和删除元素</li><li>4. 代码实现</li></ul></li></ul></div><p></p>
<br>
<h2 id="1-节点结构">1. 节点结构</h2>
<pre><code class="language-js">node = {
        ele: null,
    next: null,
}
</code></pre>
<p>这里使用了 ele 作为一个节点的元素内容, next 作为下个节点的索引</p>
<br>
<h2 id="2-构造链表">2. 构造链表</h2>
<pre><code class="language-js">let next = {};
Object.assign(next, {ele:null, next:null});
next.ele = item;
</code></pre>
<p>使用了 Object.assign 函数复制了节点结构</p>
<br>
<h2 id="3-从表头插入和删除元素">3. 从表头插入和删除元素</h2>
<pre><code class="language-js"> push(item){
    let oldFirst = this.first;
    let next = {};
    Object.assign(next, {ele: null, next: null});
    next.ele = item;
    this.first = next;
    this.first.next = oldFirst;
    this.count++;
}
pop(){
    let top = this.first.ele;
    this.first = this.first.next;
    this.count--;
    return top;
}
</code></pre>
<ul>
<li>插入时先保存栈顶元素到 oldFirst, 后创建 next 节点, 置为栈顶</li>
<li>删除时移除栈顶元素并返回</li>
</ul>
<br>
<h2 id="4-代码实现">4. 代码实现</h2>
<p><strong>链表类</strong></p>
<pre><code class="language-js">// 类定义
class Stack{
constructor() {
    // 栈顶元素, 包括 next 和 ele
    this.first = null;
    this.count = 0;
}
isEmpty(){
    return this.count === 0;
}
size(){
    return this.count;
}
push(item){
    let oldFirst = this.first;
    let next = {};
    Object.assign(next, {ele: null, next: null});
    next.ele = item;
    this.first = next;
    this.first.next = oldFirst;
    this.count++;
}
pop(){
    let top = this.first.ele;
    this.first = this.first.next;
    this.count--;
    return top;
}
// 下回分解迭代器
// (){
//
// }
}
</code></pre>
<p><strong>使用方式</strong></p>
<pre><code class="language-js">const stack = new Stack();

// 可以使用任意类型放入
stack.push(20);
stack.push('小歪');
stack.push();
stack.push({name: '张三'});

let pop = stack.pop();
// pop: { name: '张三' }
pop = stack.pop();
// [ 20, 30 ]
pop = stack.pop();
// 小歪
pop = stack.pop();
// 20
console.log(stack);
// Stack { first: null, count: 0 }
</code></pre>
<p>代码可以按要求运行 √</p>
<p><img src="http://cdn.xiaxiang.tech/image/blogs/%E7%AE%97%E6%B3%95/1/1_1.png"></p>


</div>
<div id="MySignature" role="contentinfo">
    希望读者在看完后能提出意见, 点个赞, 鼓励一下, 我们一起进步. 加油 !!<br><br>
来源:https://www.cnblogs.com/xiaxiangx/p/14276707.html
頁: [1]
查看完整版本: JavaScript 算法 1_1 下压堆栈 (链表实现)