/**
* 链式栈的实现
* 相当于只能在头部插入和删除的单链表
*/
public class LinkedStack
{
private static final String TAG = "LinkedStack";
private int size = 0;
private StackNode top = null;
class StackNode
{
Object value;
StackNode next = null;
StackNode(Object obj)
{
this.value = obj;
}
}
public void push(Object obj)
{
StackNode snode = new StackNode(obj);
snode.next = top;
top = snode;
size++;
}
public Object pop() throws Exception
{
if (top == null) throw new Exception("空栈!");
Object obj = top.value;
top = top.next;
size--;
return obj;
}
public int getSize()
{
return size;
}
public boolean isEmpty()
{
return top == null;
}
public void display() throws Exception
{
if (top == null) throw new Exception("空栈!");
StackNode cur = top;
while (cur != null)
{
System.out.print(cur.value.toString() + "->");
cur = cur.next;
}
}
public static void main(String[] args) throws Exception
{
LinkedStack lk = new LinkedStack();
lk.push("你好");
lk.push("qeqwe");
lk.push("rrr");
lk.push("htht");
lk.push("5655");
lk.push("你");
lk.push("好");
lk.display();
System.out.println("
" + lk.getSize());
lk.pop();
lk.pop();
lk.pop();
lk.display();
System.out.println("
" + lk.getSize());
}
}