《Java数据结构与算法》笔记-CH5-链表-4用链表实现堆栈
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《Java数据结构与算法》笔记-CH5-链表-4用链表实现堆栈相关的知识,希望对你有一定的参考价值。
1 //用链表实现堆栈 2 /** 3 * 节点类 4 */ 5 class LinkS { 6 private long data; 7 public LinkS next; 8 9 public LinkS(long d) { 10 this.data = d; 11 } 12 13 public String toString() { 14 return String.valueOf(data); 15 } 16 } 17 18 /** 19 * 链表类 20 */ 21 class LinkSList { 22 private LinkS first; 23 24 public LinkSList() { 25 first = null; 26 } 27 28 public void insertFirst(LinkS node) { 29 node.next = first; 30 first = node; 31 } 32 33 public LinkS deleteFirst() { 34 LinkS temp = first; 35 first = first.next; 36 return temp; 37 } 38 39 public boolean isEmpty() { 40 return first == null; 41 } 42 43 public String toString() { 44 if (isEmpty()) 45 return "[]"; 46 StringBuilder sb = new StringBuilder(); 47 sb.append("["); 48 LinkS curr = first; 49 while (curr != null) { 50 sb.append(curr.toString()).append(","); 51 curr = curr.next; 52 } 53 sb.deleteCharAt(sb.length() - 1); 54 sb.append("]"); 55 return sb.toString(); 56 } 57 } 58 59 /** 60 * 栈 61 */ 62 class LinkStack { 63 private LinkSList linkList; 64 65 public LinkStack() { 66 this.linkList = new LinkSList(); 67 } 68 69 public void push(LinkS l) { 70 this.linkList.insertFirst(l); 71 } 72 73 public LinkS pop() { 74 return this.linkList.deleteFirst(); 75 } 76 77 public boolean isEmpty() { 78 return this.linkList.isEmpty(); 79 } 80 81 public String toString() { 82 return this.linkList.toString(); 83 } 84 85 public void display() { 86 System.out.println(toString()); 87 } 88 } 89 90 public class LinkStackDemo { 91 public static void main(String[] args) { 92 LinkStack stack = new LinkStack(); 93 for (int i = 0; i < 5; i++) { 94 LinkS l = new LinkS(i); 95 stack.push(l); 96 stack.display(); 97 } 98 while (!stack.isEmpty()) { 99 System.out.print("pop出" + stack.pop()); 100 System.out.print("现在栈为:"); 101 stack.display(); 102 } 103 } 104 }
以上是关于《Java数据结构与算法》笔记-CH5-链表-4用链表实现堆栈的主要内容,如果未能解决你的问题,请参考以下文章