当前位置: 代码迷 >> 综合 >> 数据结构与算法之美 栈的代码实现
  详细解决方案

数据结构与算法之美 栈的代码实现

热度:97   发布时间:2024-02-23 13:03:06.0

java

// 基于数组实现的顺序栈
public class ArrayStack {private String[] items;  // 数组private int count;       // 栈中元素个数private int n;           // 栈的大小// 初始化数组,申请一个大小为 n 的数组空间public ArrayStack(int n) {this.items = new String[n];this.n = n;this.count = 0;}// 入栈操作public boolean push(String item) {// 数组空间不够了,直接返回 false,入栈失败。if (count == n) return false;// 将 item 放到下标为 count 的位置,并且 count 加一items[count] = item;++count;return true;}// 出栈操作public String pop() {// 栈为空,则直接返回 nullif (count == 0) return null;// 返回下标为 count-1 的数组元素,并且栈中元素个数 count 减一String tmp = items[count-1];--count;return tmp;}
}

swift

public struct Stack<T> {fileprivate var array = [T]()public var isEmpty: Bool {return array.isEmpty}public var count: Int {return array.count}public mutating func push(_ element: T) {array.append(element)}public mutating func pop() -> T? {return array.popLast()}public var top: T? {return array.last}
}//新建一个栈
var stackOfAnimals = Stack(array: ["lion", "elephant", "giraffe"])//压栈
stackOfAnimals.push("zebra")//结果是:["lion", "elephant", "giraffe", "zebra"]
print(stackOfAnimals.array)//出栈
stackOfAnimals.pop()//栈顶的元素是:"giraffe"
stackOfAnimals.top//false
stackOfAnimals.isEmpty

ES6 栈结构代码

push(element):push是进栈操作,其中element是需要进栈的元素,返回操作成功与否布尔值。
pop():pop移除栈顶元素操作,返回移除的栈顶元素。
size():获取栈中的栈元素数量,返回一个数字。
isEmpty():判断栈是否为空,返回一个布尔值。
peek():返回栈顶元素,但不移除栈顶元素。
bottom():返回栈底元素。
clear():清除所有栈元素,返回操作成功与否布尔值。class Stack{constructor(){this.lists = [];}size(){return this.lists.length;}isEmpty(){return this.lists.length === 0;}peek(){const topIndex = this.size() -1;return this.lists[topIndex];}bottom(){return this.list[0];}push(element){this.lists.push(element);return true;}pop(){return this.lists.pop();}clear(){this.lists = [];return true;}toString(){let result = "";this.lists.forEach(value=>{result = result + ""+value;});return result;}
}

ES5 栈结构代码

push(element):push是进栈操作,其中element是需要进栈的元素,返回操作成功与否布尔值。
pop():pop移除栈顶元素操作,返回移除的栈顶元素。
size():获取栈中的栈元素数量,返回一个数字。
isEmpty():判断栈是否为空,返回一个布尔值。
peek():返回栈顶元素,但不移除栈顶元素。
bottom():返回栈底元素。
clear():清除所有栈元素,返回操作成功与否布尔值。function Stack(){this.lists = [];
}
Stack.prototype.push = function(element){this.lists.push(element);return true;
}
Stack.prototype.pop = function(){return this.lists.pop();
}
Stack.prototype.clear = function(){this.lists = [];return true;
}
Stack.prototype.peek = function(){var topIndex = this.size() -1;return this.lists[topIndex];
}
Stack.prototype.size = function(){return this.lists.length;
}
Stack.prototype.isEmpty = function(){return this.lists.length === 0;
}
Stack.prototype.bottom = function(){return this.lists[0];
}
Stack.prototype.toString = function(){var result = "";for(var i=0;i<this.lists.length;i++){result = result + '' +this.lists[i];}return result;
}