Java栈的实现数组和链表
时间:2021-07-27 17:32:46
收藏:0
阅读:0
一、栈结构
栈是一种,先进后出,后进先出的数据结构,只有一端能够进行操作,是一种操作受限制的线形表
二、栈的实现
1. 通过数组实现
1 2 3 import java.util.Arrays; 4 5 //栈数组实现 6 public class ArrayStack { 7 //定义一个数组存储数据 8 private String stack[]; 9 //栈中元素个数 10 private int count; 11 //栈大小 12 private int n; 13 14 public ArrayStack(int n) { 15 this.stack = new String[n]; 16 this.n = n; 17 this.count = 0; 18 } 19 20 @Override 21 public String toString() { 22 return "ArrayStack{" + 23 "stack=" + Arrays.toString(stack) + 24 ", count=" + count + 25 ", n=" + n + 26 ‘}‘; 27 } 28 29 /** 30 * push数据 31 * 32 * @param item 33 * @return 34 * @throws Exception 35 */ 36 public boolean push(String item) throws Exception { 37 if (n == count) { 38 throw new Exception(); 39 } 40 stack[count] = item; 41 count++; 42 return true; 43 } 44 45 public String pop() throws Exception { 46 if (n == 0) { 47 throw new Exception(); 48 } 49 String tmp = stack[count - 1]; 50 stack[count-1] = null; 51 count--; 52 return tmp; 53 54 } 55 56 public static void main(String[] args) throws Exception { 57 ArrayStack arrayStack = new ArrayStack(5); 58 59 arrayStack.push("a"); 60 System.out.println(arrayStack); 61 62 arrayStack.push("b"); 63 System.out.println(arrayStack); 64 65 String pop = arrayStack.pop(); 66 System.out.println(pop); 67 System.out.println(arrayStack); 68 69 70 } 71 72 }
2. 通过链表实现
链表节点
1 public class Node { 2 public String data; 3 public Node next; 4 5 public Node() { 6 } 7 8 public Node(String data) { 9 this.data = data; 10 } 11 12 public Node(String data, Node next) { 13 this.data = data; 14 this.next = next; 15 } 16 17 @Override 18 public String toString() { 19 return "Node{" + 20 "data=‘" + data + ‘\‘‘ + 21 ‘}‘; 22 } 23 }
实现
1 public class LinkedListStack { 2 private Node head; 3 4 public LinkedListStack() { 5 } 6 7 @Override 8 public String toString() { 9 StringBuffer sb = new StringBuffer(); 10 Node tmp = head; 11 while (tmp!=null){ 12 sb.append(tmp.data).append(","); 13 tmp = tmp.next; 14 } 15 16 return sb.toString(); 17 } 18 19 public boolean push(String item){ 20 head = new Node(item,head); 21 return true; 22 } 23 24 public String pop() throws Exception{ 25 if(head==null){ 26 throw new Exception(); 27 } 28 29 String tmp = head.data; 30 head =head.next; 31 return tmp; 32 } 33 34 public static void main(String[] args) throws Exception{ 35 LinkedListStack stack = new LinkedListStack(); 36 stack.push("a"); 37 System.out.println(stack); 38 39 stack.push("b"); 40 System.out.println(stack); 41 42 String pop = stack.pop(); 43 System.out.println(pop); 44 System.out.println(stack); 45 46 47 } 48 }
评论(0)