Java实现栈及其操作

使用Java实现栈及相关操作

栈的特点是FILO,先进去的元素最后才出。

使用Java实现栈,先定义一个栈的结点元素 即 stacknode类 该类包含一个属性——元素值 和赋值、打印的操作 

再实现栈操作,将各个元素存储在arraylist中。

栈操作包括 压栈 出栈 遍历

import java.util.ArrayList;

//使用java.arraylist实现stack

//stack的每个结点元素:值
class stacknode{
	int val=0;
	
	//结点初始化
	public stacknode(int val) {
		this.val=val;
	}
	//打印该节点
	public void print()
	{
		System.out.println("The value is "+val);
	}
}

//stack主类
public class Stack {

	//stack的size和max size
	int top=0;
	final int Max_Size=100;
	
	//定义一个空arraylist命名为stacklist来存放stack元素
	ArrayList<stacknode> stacklist =new ArrayList<stacknode>();
	
	//自顶依次遍历stack
	void traverse()
	{
		for(int i=top;i>0;i--)
		{
			
			System.out.print(stacklist.get(i-1).val+"->");
			
		}
		System.out.println("\\");
	}
	
	//压栈操作
	void push(stacknode e)
	{
		if(top<Max_Size)
		{
			stacklist.add(e);
			top++;
		}
		else
		{
			System.err.println("push error");
		}
	}
	//出栈操作
	stacknode pop()
	{
		if(top>0)
		{
			stacknode e=stacklist.get(top-1);
			stacklist.remove(top-1);
			top--;
			return e;
		}
		else
		{
			System.err.println("pop error");
			return null;
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//生成三个结点 并利用生成的结点构建一个栈:依次压栈
		Stack s=new Stack();
		for(int i=0;i<3;i++)
		{
			s.push(new stacknode(i));
		}
		
		//遍历操作
		s.traverse();
		
		//依次出栈
		stacknode temp=s.pop();
		temp.print();
		temp=s.pop();
		temp.print();
		temp=s.pop();
		temp.print();
	}

}
发布了52 篇原创文章 · 获赞 27 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_37457432/article/details/104143797
今日推荐