栈(Stack)

112 阅读1分钟

只允许在一端进行插入或删除操作的线性表,栈是一种典型的后进先出 (Last in First Out) 的数据结构。

stack1.jpg

基本操作

  1. push(x)
  2. pop()
  3. top()
  4. isEmpty()

以上几种操作的时间复杂度都是 O(1)。

实现

数组实现

public class Stack {
	
	private static final int MAX_SIZE  = 100;

	private int[] elements = new int[MAX_SIZE];
	private int top = -1

	public void push(int x) {
		if (top >= MAX_SIZE - 1) {
                    return;
		}
		elements[++top] = x;
	}

	public void pop() {
		if (isEmpty()) {
                    return;
		}
		top--;
	}

	public int top() {
		if (isEmpty) {
                    throw new IllegalStateException();
		}
		return elements[top];
	}

	public boolean isEmpty() {
		return top != -1;
	}
}

链表实现

在链表的头部插入和删除才满足时间复杂度为O(1)

public class Stack {

	private ListNode top;

	public void push(int x) {
		ListNode temp = new ListNode(x, top);
		top = temp;
	}

	public void pop() {
		if (isEmpty()) {
			return;
		}
		top = top.next;
	}

	public int top() {
		if (isEmpty()) {
			throw new IllegalStateException();
		}
		return top.data;
	}
	
	public boolean isEmpty() {
		return top == null;
	}

	private static class ListNode {
		private int data;
		private ListNode next;

		ListNode(int data, ListNode next) {
			this.data = data;
			this.next = next;
		}
	}
}