1 class Node { 2 char s; 3 Node next; 4 5 public Node(char s) { 6 // TODO Auto-generated constructor stub 7 this.s = s; 8 next= null; 9 } 10 } 11 12 class LinkStack { 13 Node sp; 14 15 public LinkStack() { 16 // TODO Auto-generated constructor stub 17 sp = null; 18 } 19 20 public boolean isEmpty() { 21 return sp == null; 22 } 23 24 public void push(char c) { 25 Node node = new Node(c); 26 27 node.next = sp; 28 sp = node; 29 } 30 31 public char pop() { 32 Node tmp; 33 34 if (isEmpty()) 35 return 0; 36 37 tmp = sp; 38 sp = sp.next; 39 return tmp.s; 40 } 41 } 42 43 public class stack { 44 public static void main(String[] args) { 45 LinkStack s1 = new LinkStack(); 46 LinkStack s2 = new LinkStack(); 47 char str[] = "hello world".toCharArray(); 48 49 s1.push(' '); 50 for (char c : str) { 51 s1.push(c); 52 } 53 54 while (!s1.isEmpty()) { 55 char c; 56 c = s1.pop(); 57 58 if (c == ' ') { 59 while (!s2.isEmpty()) { 60 System.out.print(s2.pop()); 61 } 62 System.out.print(" "); 63 } else 64 s2.push(c); 65 } 66 } 67 }
转载于:https://www.cnblogs.com/robin-he0221/archive/2012/09/09/LinkStack_by_java.html