链表实现栈、队列

 栈结构:

对数据的存储利用链式存储;所有的数据类型都支持;栈的方法: 压栈、 弹栈、 判空。

队列结构:

对数据的存储利用链式存储;所有的数据类型都支持; 队列的方法:入队、出队、判空。

package repeat_job1;

public class Stack_Queue {
	private Object data;
	private Stack_Queue next,First,obj2=null,temp=this;
	private int flag=0;
	public Stack_Queue(){}
	public Stack_Queue(Object data){
		this.data=data;
	}
	public void push(Object data)
	{
		Stack_Queue obj1;
		obj1=new Stack_Queue(data); 
		obj1.next=this.next;
		this.next=obj1;	
	}
	public boolean stack_IsEmpty()
	{
		temp=temp.next;
		return temp==null;
		
	}
	public Object pop()
	{
		return temp.data;
	}
	public void in_Queue(Object data)
	{
		Stack_Queue obj3;
		obj3=new Stack_Queue(data);
		if(obj2==null)//obj2.next会出现空指针!
		{
			obj2=obj3;
			First=obj2;
			obj2.next=this;
		}
		obj3.next=this;
		obj2.next=obj3;
		obj2=obj3;//obj2要紧跟obj3;

	}
	public boolean queue_IsEmpty()
	{
		if(flag==1)
		{
			First=First.next;
		    return First.next==null;
		}
		else
		{
			return First.next==null;
			}
		
	}
	public Object out_Queue()
	{
        flag=1;
		return First.data;
	}
	

}
import repeat_job1.Stack_Queue;
public class Stack_Queue_Test {
	public static void main(String[] args)
	{
		Stack_Queue obj1=new Stack_Queue();
		obj1.push("hello");
		obj1.push("world");
		obj1.push("张三");
		obj1.push(23333);
		System.out.println("出栈:");
		while(!obj1.stack_IsEmpty())
		{
			System.out.print(obj1.pop()+" ");
		}
		System.out.println();
		Stack_Queue obj2=new Stack_Queue();
		obj2.in_Queue("hello");
		obj2.in_Queue("world");
		obj2.in_Queue("张三");
		obj2.in_Queue(23333);
		System.out.println("出队:");
		while(!obj2.queue_IsEmpty())
		{
			System.out.print(obj2.out_Queue()+" ");
		}
	}

}




原文地址:https://www.cnblogs.com/zyh2017/p/5001730.html