package 数据结构;
public class Link
{
public int data ;
public Link next ;//记录下一个节点
public Link ( int data )
{
this.data = data ;
}
}
package 数据结构;
public class LinkStack
{
private Link top ;//栈顶
//入栈
public void push ( int data )
{
Link newLink = new Link ( data ) ;
// 如果为空 , 直接将新节点变为栈顶
if ( isEmpty () )
{
top = newLink ;
return ;//退出
}
//不为空,将新节点的next指向原栈顶
newLink.next = top ;
//新节点成为栈顶
top = newLink ;
}
//出栈
public Link pop ()
{
if ( isEmpty () )
{
System.out.println ( "当前栈中没有元素" );
return null;
}
Link temp = top ;//存放要出栈的节点
top = top.next ;//栈顶元素变为原栈顶的next
return temp ;
}
//判断是否为空
public boolean isEmpty ()
{
return top == null ;
}
//遍历
public void display ()
{
if ( isEmpty () )
{
System.out.println ( "栈为空" );
return ;
}
Link current = top ;//记录遍历到哪儿
while ( current != null )
{
System.out.print ( current.data + " " );
current = current.next ;
}
System.out.println ();
}
}