如何实现栈
采用数组和链表两种方式来实现栈
数组实现栈,代码如下:
package 如何实现栈;
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; //每次数组扩充的容量
stack = Arrays.copyOf(stack, newLen);
}
}
public static void main(String[] args) {
MyStack<Integer> s = new MyStack<>();
s.push(1);
s.push(2);
System.out.println("栈中元素个数:"+ s.size);
System.out.println("栈顶元素为:" + s.pop());
System.out.println("栈顶元素为:" + s.pop());
}
}
链表的方式实现栈,代码如下:
public class Node<E> {
Node<E> next = null;
E data;
public Node(E data){
this.data = data;
}
}
package 如何实现栈;
/**
* 用链表方式实现栈
* @author dream
*
* @param <E>
*/
public class MyStack2<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(isEmpty()){
return null;
}
E data = top.data;
top = top.next;
return data;
}
public E peek(){
if(isEmpty()){
return null;
}
return top.data;
}
}
时间: 2024-10-31 03:49:41