/**
* 链式栈的实现
* 相当于只能在头部插入和删除的单链表
*/
public class LinkedStack
{
private static final String TAG = "LinkedStack";
/*长度和头指针*/
private int size = 0;
private StackNode top = null;//top
/*节点类*/
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.pop();
//lk.display();
lk.push("你好");
lk.push("qeqwe");
lk.push("rrr");
lk.push("htht");
lk.push("5655");
lk.push("你");
lk.push("好");
lk.display();
System.out.println("\n" + lk.getSize());
lk.pop();
lk.pop();
lk.pop();
lk.display();
System.out.println("\n" + lk.getSize());
}
}
Java栈(链式实现)
最新推荐文章于 2022-03-16 21:59:39 发布