import java.util.*;
class Node{
int val;
Node next=null;
public Node(int val){
this.val=val;
}
}
class LinkStack{
Node top;
int size;
public LinkStack(){
top=null;
size=0;
}
public void Push(int x){
Node s=new Node(x);
s.next=top;
top=s;
size++;
}
public int Pop(){
if(top==null)
{
System.out.println("The stack is empty");
return -1;
}
int x=top.val;
top=top.next;
size--;
return x;
}
public int getTop(){
if(isEmpty()) throw new NullPointerException("The Stack is empty!");
return top.val;
}
public boolean isEmpty()
{
if(top==null)
return true;
return false;
}
public int getSize(){
return size;
}
public void PrintStack(){
if(top==null)
{
System.out.println("The stack is empty!");
return;
}
Node s=top;
while(s.next!=null)
{
System.out.print(s.val+"-->");
s=s.next;
}
System.out.println(s.val);
return;
}
}
public class Main{
public static void main(String args[]){
LinkStack stack=new LinkStack();
stack.Push(3);
stack.Push(4);
stack.Push(5);
stack.PrintStack();
int t=stack.Pop();
System.out.println("弹出栈顶元素:"+t);
stack.PrintStack();
System.out.println("栈的元素个数:"+stack.getSize());
System.out.println("栈顶元素:"+stack.getTop());
if(stack.isEmpty())
System.out.println("The stack is empty!");
else
System.out.println("The stack is not empty!");
stack.PrintStack();
}
}
链栈的创建,入栈,出栈,取栈顶元素,判空,元素个数
最新推荐文章于 2024-04-23 15:06:57 发布