java:队列模拟(自定义链表结构 +LinkedList )

package com.queue;

/*
 * 用链表结构实现的队列:链表节点类型 ,队列的首节点、尾节点
 * //1.元素进入队列,插在链尾
 * //2.元素出队列,删除对首元素
 * */

//链表节点
class Node
{
	int data;
	Node next;
	 
	public Node(int data)
	{
		this.data = data;
	}
}

class LinkedQueue
{
	Node head;  //对首
	Node tail; //队尾
	
	//1.元素进入队列,插在链尾
	public void push(int val)
	{ 
		//定义新节点
		Node newNode = new Node(val);
		newNode.next = null;
		
		//对首为空时,插在对首
		if(head == null)
		{
			head = newNode;
			tail = head;
		}
		
		//对首不为空时,插在队尾
		else
		{
			tail.next = newNode;
			tail = newNode;
		}
	}
	
	//2.元素出队列,删除对首元素
	public void pop()
	{
		int val;
		//先判断队列是否为空
		if(isEmpty())
		{
			System.out.println("队列已空");
			return;
		}
		else
		{
			val = head.data;
			System.out.print(val +" ");
			
			head = head.next;
		}
	}
	
	//判断队列是否为空
	public boolean isEmpty()
	{
		if(head == null)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
}


public class TestLinkedQueue 
{
	public static void main(String[] args)
	{
		LinkedQueue lq = new LinkedQueue();
		
		System.out.print("元素入队列:");
		for(int i = 0; i < 5; i++)
		{
			lq.push(i);
			System.out.print(i +" ");
		}
		System.out.println();
		
		System.out.print("元素出队列:");
		for(int i = 0; i < 5; i++)
		{
			lq.pop();
		}
		System.out.println();
	}
}


package com.queue;

import java.util.LinkedList;

//用数组结构实现的队列
class LinkedListQueue
{
	private LinkedList arr = new LinkedList();  //用linkedList集合模拟队列中的存储空间
	private int size = 0; //队列的长度
	
	//元素入队列,在集合尾添加元素
	public void push(int val)
	{
		arr.add(val);
		size ++;
	}
	
	//元素出队列,删除集合首元素
	public void pop()
	{
		int val;
		size --;
		val = (Integer)arr.removeFirst();
		System.out.print(val +" ");
	}
	
}


public class TestLinkedListQueue
{
	public static void main(String[] args) 
	{
		LinkedListQueue aq = new LinkedListQueue();
		
		System.out.print("元素入队列:");
		for(int i = 10; i > 5; i--)
		{
			aq.push(i);
			System.out.print(i +" ");
		}
		System.out.println();
		
		System.out.print("元素出队列:");
		for(int i = 5; i > 0; i--)
		{
			aq.pop();
		}
		System.out.println();
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值