直接上代码,push时直接往数组末尾存,pop时直接在数组末尾取
/**
* @create 2017-09-22 21:23
*/
public class StackDemo {
public static int N = 0;
public static int[] a = new int[1];
public void resize(int n) { //动态调整数组大小
int t[] = new int[n];
for (int i = 0; i < N; i++) {
t[i] = a[i];
}
a = t;
}
public void push(int i) {
a[N++] = i;
if (isFull()) {
resize(size() * 2);
}
}
public int peek() { //查看栈顶元素
if (N == 0) {
throw new RuntimeException("Stack is empty.");
}
return a[N - 1];
}
public boolean isFull() {
return N >= size() - 1;
}
public boolean isEmpty() {
return N == 0;
}
public int pop() {
if (N == 0) {
throw new RuntimeException("Stack is empty.");
}
int t = a[--N];
if (N <= size() / 2) {
resize(size() / 2);
}
return t;
}
public int size() {
return a.length;
}
public static void main(String[] args) {
StackDemo s = new StackDemo();
for (int i = 0; i < 10; i++) {
s.push(i);
}
while (!s.isEmpty()) {
System.out.println(s.pop());
}
}
}
当然,也可以用单链表来实现栈,直接在链表头部删除或插入元素即可
/**
* @create 2017-09-22 21:23
*/
public class StackDemo {
public static int len = 0;
Node head = null;
private class Node {
int num;
Node next;
public Node(int num) {
this.num = num;
this.next = null;
}
}
public void push(int n) {
if (isEmpty()) {
head = new Node(n);
} else { //在链表头部插入新的结点
Node old = head;
head = new Node(n);
head.next = old;
}
len++;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty.");
}
int t = head.num;
head = head.next;
len--;
return t;
}
public int peek() { //查看栈顶元素
if (isEmpty()) {
throw new RuntimeException("Stack is empty.");
}
return head.num;
}
public int size() {
return len;
}
public boolean isEmpty() {
return head == null; //也可以是len == 0
}
public static void main(String[] args) {
StackDemo s = new StackDemo();
for (int i = 0; i < 10; i++) {
s.push(i);
}
System.out.println("size: " + s.size());
while(!s.isEmpty()) {
System.out.println(s.pop());
}
}
}