算法思想:
方法一:采用数组的方式来实现栈,以下只是简单的实现,没有对进栈、出栈进行同步操作,过程是非线程安全的。
方法二:采用链表的方式来实现栈,以下只是简单的实现,没有对进栈、出栈进行同步操作,过程是非线程安全的。
方法一代码如下:
package com.haobi;
import java.util.Arrays;
/*
* 用数组来实现栈
*/
public class MyStack<E>{
private Object[] stack;
private int size;//数组中存储元素的个数
public MyStack() {
stack = new Object[10];//初始长度为10
}
//判断栈是否为空
public boolean isEmpty() {
return size == 0;
}
//栈顶元素
public E peek() {
if(isEmpty()) {
return null;
}
return (E)stack[size-1];
}
//出栈
public E pop() {
E e = peek();
stack[size - 1] = null;
size--;
return e;
}
//入栈
public E push(E item) {
ensureCapacity(size+1);
stack[size++] = item;
return item;
}
//判断数组是否已满,若已满,则扩充数组空间
private void ensureCapacity(int size) {
int len = stack.length;
if(size>len) {//数组已满
int newLen = 10;//每次数组扩充的容量
//Arrays.copyOf用于复制指定的数组内容以达到扩容的目的
//该方法对不同的基本数据类型都有对应的重载方法
stack = Arrays.copyOf(stack, newLen);
}
}
public static void main(String[] args) {
MyStack<Integer> s = new MyStack<Integer>();
s.push(1);//进栈
s.push(2);//进栈
s.push(3);//进栈
System.out.println("栈中元素个数为:"+s.size);
System.out.println("栈顶元素为:"+s.pop());//输出栈顶元素,并进行出栈操作
System.out.println("栈顶元素为:"+s.pop());//输出栈顶元素,并进行出栈操作
}
}
程序输出结果如下:
栈中元素个数为:3
栈顶元素为:3
栈顶元素为:2
方法二代码如下:
package com.haobi;
/*
* 用链表来实现栈
*/
class Node<E>{
Node<E> next = null;
E data;
public Node(E data) {
this.data = data;
}
}
public class Stack<E> {
Node<E> top = null;
//判断是否为空
public boolean isEmpty() {
return top == null;
}
//入栈
public void push(E data) {
Node<E> newNode = new Node<E>(data);
newNode.next = top;
top = newNode;
}
//出栈
public E pop() {
if(this.isEmpty())
return null;
E data = top.data;
top = top.next;
return data;
}
//栈顶元素
public E peek() {
if(isEmpty()) {
return null;
}
return top.data;
}
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
s.push(1);//进栈
s.push(2);//进栈
s.push(3);//进栈
System.out.println("栈顶元素为:"+s.peek());//输出栈顶元素
s.pop();//出栈
System.out.println("栈顶元素为:"+s.peek());//输出栈顶元素
}
}
程序输出结果如下:
栈顶元素为:3
栈顶元素为:2