栈(存储结构链表)--Java实现
1 /*用链表实现栈--链栈 2 * */ 3 public class MyLinkedStack { 4 public MyLinkedList linklist; 5 int items; 6 7 public MyLinkedStack() { 8 items = 0; 9 linklist = new MyLinkedList(); 10 } 11 12 public boolean isEmpty(){ 13 return linklist.isEmpty(); 14 } 15 16 public void push(int key){ 17 linklist.insertFirst(key); 18 items++; 19 } 20 21 public Link pop(){ 22 Link temp = linklist.deleteFirst(); 23 items--; 24 return temp; 25 } 26 27 public void diaplayStack(){ 28 System.out.println("stack--top--to--bottom"); 29 linklist.displayLinkedList(); 30 } 31 32 public int size(){ 33 return items; 34 } 35 36 public Link getTop(){ 37 return linklist.deleteFirst(); 38 } 39 40 public static void main(String[] args) { 41 MyLinkedStack stack = new MyLinkedStack (); 42 for(int i = 0; i < 7; i++){ 43 stack.push(i); 44 } 45 46 stack.diaplayStack(); 47 stack.pop(); 48 stack.diaplayStack(); 49 System.out.println(stack.size()); 50 } 51 52 }
该链表事先已经定义好了,可以直接使用。