1、棧的特色node
一、線性數據結構數組
二、後進先出數據結構
2、使用數組來實現棧this
//使用數組來實現棧 public class MyArrayStack<E> { //保存數據 private Object[] items; //棧的 容量 private int capacity; //棧的數據個數 private int size; public MyArrayStack(int capacity){ this.capacity = capacity; this.items = new Object[capacity]; } //入棧 public boolean push(E item){ //棧已經滿了 if(size == capacity){ return false; } items[size++] = item; return true; } //出棧 @SuppressWarnings("unchecked") public E pop() { if(size == 0){ return null; } E e = (E)items[size-1]; items[--size] = null; return e; } }
3、使用鏈表來實現棧、spa
//使用鏈表建立棧 public class MyLinkedStack<E> { //節點存儲元素信息 private static class Node<E>{ E item; Node<E> next;//下一個節點 Node(E item, Node<E> next){ this.item = item; this.next = next; } } //棧的 容量 private int capacity; //棧的數據個數 private int size; //頭節點 private Node<E> head; public MyLinkedStack(int capacity){ this.capacity = capacity; } //入棧 public boolean push(E item){ //棧已經滿了 if(size == capacity){ return false; } //建立新節點,head指向新的節點 Node<E> node = new Node<>(item,head); head = node; size++; return true; } //出棧 public E pop() { if(size == 0){ return null; } E e = head.item; head.item = null;//方便GC head = head.next; size--; return e; } }