1. 利用顺序表实现,即使用尾插 + 尾删的方式实现
2. 利用链表实现,则头尾皆可 相对来说,顺序表的实现上要更为简单一些,所以我们优先用顺序表实现栈
package stack; public class Test { public static void main(String[] args) { myStack1 m = new myStack1(); m.push(1); m.push(2); m.push(3); m.push(4); m.push(5); m.push(6); System.out.println(m.pop()); System.out.println(m.peek()); myStack2 m2=new myStack2(); m2.push(7); m2.push(8); m2.push(8); m2.push(9); System.out.println(m2.pop()); System.out.println(m2.peek()); System.out.println(m2.peek()); } } //数组实现栈 class myStack1 { private int[] elem = new int[2]; private int size = 0; //压栈 public void push(int e) { if (isFull()) { this.elem = expend(elem); } elem[size] = e; size++; } //出栈 public int pop() { return elem[--size]; } //查看栈顶元素 public int peek() { return elem[size - 1]; } //判断是否满了 public boolean isFull() { if (size == elem.length) { return true; } return false; } public int[] expend(int[] e) { int[] newElem = new int[e.length * 2]; return newElem; } } //链表实现栈 class myStack2 { private int data; private myStack2 next; public myStack2(){ } public myStack2(int data) { this.data = data; } public myStack2 head; //压栈 public void push(int data) { myStack2 m = new myStack2(data); if (this.head == null) { this.head = m; } m.next=this.head; this.head=m; } //出栈 public int pop(){ int ret=this.head.data; this.head=this.head.next; return ret; } //产看栈顶元素 public int peek(){ return this.head.data; } }
整个思路不是很严谨,只能呈献出比较简单的栈。
Java实现栈
最新推荐文章于 2024-08-16 23:08:28 发布