一、以数组为内核的栈的实现:
1 package data.struct.algorithm; 2 3 class Stackx { 4 private int maxSize; 5 private int[] stackArray; 6 private int top; 7 8 //自己的错误出现在这个地方,错误写法:maxSize=this.maxSize; 9 public Stackx(int maxSize) { 10 this.maxSize = maxSIze; 11 stackArray = new int[maxSize]; 12 top = -1; 13 } 14 15 public void push(int j) { 16 stackArray[++top] = j; 17 } 18 19 public int pop() { 20 return stackArray[top--]; 21 } 22 23 public int peek() { 24 return stackArray[top]; 25 } 26 27 public boolean isEmpty() { 28 return top==-1; 29 } 30 31 public boolean isFull() { 32 return top==maxSize-1; 33 } 34 } 35 36 public class StackApp { 37 38 /** 39 * @param args 40 */ 41 public static void main(String[] args) { 42 43 Stackx theStackx = new Stackx(10); 44 theStackx.push(20); 45 theStackx.push(40); 46 theStackx.push(60); 47 theStackx.push(80); 48 theStackx.push(1); 49 theStackx.push(67); 50 theStackx.push(78); 51 theStackx.push(23); 52 System.out.println(theStackx.peek()); 53 while (!theStackx.isEmpty()) { 54 System.out.print(theStackx.pop()+" "); 55 } 56 System.out.println(); 57 } 58 59 }
二、用链表来实现栈
1 package data.struct.algorithm; 2 3 /* 4 * 用链表实现栈,用的就是insertFirst()和deleteFirst方法,即插入和删除结点都在链表头进行 5 */ 6 class Node { 7 public int data; 8 public Node next; 9 10 public Node(int data, Node next) { 11 this.data = data; 12 this.next = next; 13 } 14 } 15 16 class LinkList { 17 private Node head; 18 19 public LinkList() { 20 head = null; 21 } 22 23 public void insertFirst(int data) { 24 Node newNode = new Node(data, null); 25 newNode.next = head; 26 head = newNode; 27 } 28 29 public Node deleteFirst() { 30 if (head == null) { 31 return null; 32 } 33 Node tempNode = head; 34 head = head.next; 35 return tempNode; 36 } 37 38 public boolean isEmpty() { 39 return head == null; 40 } 41 } 42 43 class LinkStack { 44 private LinkList theStack; 45 46 public LinkStack() { 47 theStack = new LinkList(); 48 } 49 50 public void push(int data) { 51 theStack.insertFirst(data); 52 } 53 54 public void pop() { 55 System.out.println(theStack.deleteFirst().data); 56 } 57 58 public boolean isEmpty() { 59 return theStack.isEmpty(); 60 } 61 } 62 63 public class LinkListStackTest { 64 65 /** 66 * @param args 67 */ 68 public static void main(String[] args) { 69 70 LinkStack theStack = new LinkStack(); 71 theStack.push(10); 72 theStack.push(20); 73 theStack.push(30); 74 theStack.push(40); 75 theStack.push(50); 76 while (!theStack.isEmpty()) { 77 theStack.pop(); 78 } 79 } 80 81 }