Use LinkedList to Implement Stack

 1 public class UseLinkedListImplementStack {
 2     private ListNode head;
 3     private int length ;
 4     public UseLinkedListImplementStack() {
 5         this.head = null ;
 6         this.length = 0;
 7     }
 8     /*             H
 9          (last in) 1->2->3->4 (1st in)
10                       o/H
11      */
12     public void push(int val){
13         ListNode node = new ListNode(val) ;
14         node.next = head ;
15         head = node ;
16         length++;
17     }
18 
19     public Integer pop(){
20         if (head == null)  return null;
21         int value = head.val ;
22         head = head.next;
23         length-- ;
24         return value ;
25     }
26 
27     public Integer peek(){
28         if (head == null) return null ;
29         return head.val ;
30     }
31 
32     public boolean isEmpty(){
33         return this.length <= 0 ;
34     }
35 
36     public int getSize(){
37         return this.length ;
38     }
39 
40     public static void main(String[] args) {
41         UseLinkedListImplementStack stack = new UseLinkedListImplementStack();
42         stack.push(1);
43         stack.push(3);
44         System.out.println(stack.getSize());
45         System.out.println(stack.peek());
46         System.out.println(stack.pop());
47         stack.push(4);
48         System.out.println(stack.peek());
49     }
50 }

 

 

posted @ 2018-03-26 07:46  davidnyc  阅读(150)  评论(0编辑  收藏  举报