算法学习笔记:自建集合数据类型(3),使用链表实现队列

使用链表实现队列和之前文章使用链表实现栈的原理基本上类似,唯一不同的是把后进先出改为了先进先出

有一点不同的是相较于栈只需要一个first变量来保存头节点,队列还需要一个last变量保存尾节点。每次enqueue都在尾节点添加一个新的元素,dequeue删除头节点元素

	public void enqueue(Item item) {
		Node oldLast = last;
		last = new Node();
		last.item = item;
		n++;
		if (n == 1) {
			first = last;
		} else {
			oldLast.next = last;
		}
	}

在enqueue代码中,注意如果此时加入的为当前队列第一个元素,需要将其设为first和last。否则记录之前的last,把last设为新加入元素,然后把之前的last的next设为新的last.

	public Item dequeue() {
		Item element = first.item;
		first = first.next;
		n--;
		return element;
	}

dequeue方法和栈里面的pop方法基本上一致

完整代码及测试数据:

import java.util.Iterator;

public class LinkedListQueue<Item> implements Iterable<Item> {

	private class Node {
		Item item;
		Node next;
	}
	
	private int n = 0;	//the length of queue
	private Node first;
	private Node last;
	
	public boolean isEmpty() {
		return n == 0;
	}
	
	
	public int size() {
		return n;
	}
	
	
	public void enqueue(Item item) {
		Node oldLast = last;
		last = new Node();
		last.item = item;
		n++;
		if (n == 1) {
			first = last;
		} else {
			oldLast.next = last;
		}
	}
	
	
	public Item dequeue() {
		Item element = first.item;
		first = first.next;
		n--;
		return element;
	}
	
	
	public Iterator<Item> iterator() {
		return new ReverseLinkedListIterator();
	}
	
	
private class ReverseLinkedListIterator implements Iterator<Item> {
		private Node current = first;
		public boolean hasNext() {
			return current != null;
		}
		public Item next() {
			Item item = current.item;
			current = current.next;
			return item;
		}
		public void remove() {
			// leave blank on purpose
		}
	}	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LinkedListQueue<Integer> test = new LinkedListQueue<Integer>();
		test.enqueue(1);
		test.enqueue(2);
		test.enqueue(3);
		test.enqueue(4);
		test.enqueue(5);
		test.dequeue();
		test.dequeue();
		test.dequeue();
		System.out.println(test.dequeue());
		
	}
}
	

备注:
对于实现Iterator的解释,查看文章《算法学习笔记:自建集合数据类型(1)使用数组实现下压栈》
https://blog.csdn.net/Raine_Yang/article/details/119923848

对于链表的解释,查看文章《算法学习笔记:自建集合数据类型(2)使用链表实现下压栈》
https://blog.csdn.net/Raine_Yang/article/details/119945560

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值