java:链栈

java:链栈_第1张图片

`import java.util.Scanner;

/**
 * 
 * @author chenqian
 * @time:2020/7/23
 * @功能:用链表来表示栈
 */
public class Dome_2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
    Zhan z = new Zhan();
    System.out.print("请输入元素的个数:");
    Scanner input = new Scanner(System.in);
    int num = input.nextInt();
    for(int i = 0;i < num;i ++)
    {
    	int sum = input.nextInt();
    	z.push(sum);
    	
    }
    System.out.println("出栈:");
    z.pop();
    	
    
    
	}

}
class Zhan{
	Hero top = null;
	public void push(int id)
	{
		Hero hero = new Hero(id);
		hero.next = top;//将新插入的结点的后继指向栈顶,
	
		top = hero;	//将新插入的结点替换成新的栈顶
	}
	public void pop()
	{
		while(true)
		{
			if(top == null)
			{
				System.out.println("已空");
				break;
			}
			else
			{
				System.out.println("出栈元素:" + top.id);
				top = top.next;
				
			}
			
		}
		
	}
	
}
class Hero{
	public int id;
	public Hero next;
	public Hero(int id)
	{
		this.id = id;
	}
	
}`

你可能感兴趣的:(java数据结构)