链栈

 

StackNode.java

1 package cn.ftf.mylinkstack;
2 
3 public class StackNode {
4     public StackNode next;
5     public Object obj;
6     
7 
8 }

MyLinkStack.java

 1 package cn.ftf.mylinkstack;
 2 
 3 import MyArrayStack.IStack;
 4 
 5 public class MyLinkStack implements IStack{
 6     private int size;
 7     private StackNode top;
 8 
 9 
10     public MyLinkStack() {
11         this.size = 0;
12         this.top = null;
13     }
14 
15     @Override
16     public void clear() {
17         top=null;
18         
19     }
20 
21     @Override
22     public boolean isEmpty() {
23         return top==null;
24     }
25 
26     @Override
27     public int length() {
28         // TODO Auto-generated method stub
29         return size;
30     }
31 
32     @Override
33     public Object peek() {
34         return top;
35     }
36 
37     @Override
38     public void push(Object obj) {
39         StackNode s=new StackNode();
40         s.obj=obj;
41         s.next=top;
42         top=s;
43         size++;
44     }
45 
46     @Override
47     public Object pop() {
48         StackNode ss=top;
49         top=top.next;
50         size--;
51         return ss;
52     }
53 
54     @Override
55     public void display() {
56         StackNode ss=top;
57         while(ss!=null) {
58             System.out.println(ss.obj);
59             ss=ss.next;
60         }
61     }
62     
63     public static void main(String[] args) {
64         MyLinkStack m=new MyLinkStack();
65         m.push("hello");
66         m.push("hello2");
67         m.push("hello3");
68         m.display();
69         System.out.println("----------------------------");
70         StackNode st=(StackNode) m.pop();
71         StackNode st2=(StackNode) m.pop();
72         m.display();
73         StackNode st3=(StackNode) m.pop();
74     }
75 
76 }

 

posted @ 2019-08-05 23:12  codeFlyer  阅读(137)  评论(0编辑  收藏  举报