LinkedQueue

简书 賈小強
转载请注明原创出处,谢谢!

package com.lab1.test1;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedQueue<Item> implements Iterable<Item> {
    private int n;
    private Node first, last;

    private class Node {
        private Item item;
        private Node next;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator<Item> {
        Node current = first;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }

    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (Item item : this) {
            builder.append(item + " ");
        }
        return builder.toString();
    }

    private boolean isEmpty() {
        return first == null;
    }

    private int size() {
        return n;
    }

    private void push(Item item) {
        Node oldlast = last;
        last = new Node();
        last.item = item;
        if (isEmpty()) {
            first = last;
        } else {
            oldlast.next = last;
        }
        n++;
    }

    private Item pop() {
        if (isEmpty()) {
            throw new NoSuchElementException("empty stack exception");
        }
        Item item = first.item;
        first = first.next;
        if (isEmpty()) {
            last = null;
        }
        n--;
        return item;
    }

    public static void main(String[] args) {
        LinkedQueue<String> stack = new LinkedQueue<>();
        System.out.println(stack);
        System.out.println(stack.size());
        System.out.println(stack.isEmpty());

        stack.push("bill");
        stack.push("jack");
        stack.push("lucy");
        System.out.println(stack);
        System.out.println(stack.size());
        System.out.println(stack.isEmpty());

        stack.pop();
        stack.pop();
        System.out.println(stack);
        System.out.println(stack.size());
        System.out.println(stack.isEmpty());
    }

}

输出


0
true
bill jack lucy 
3
false
lucy 
1
false

Happy learning !!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,678评论 25 708
  • 简书 賈小強转载请注明原创出处,谢谢! Servlet是一种允许响应请求的Java类。虽然Servlet可以响应任...
    賈小強阅读 10,643评论 1 44
  • 小时候我就是一个不爱学习的人,老师布置作业能少写就少写。上课时候逃课这些事情我都干过。记得我小学的时候很乖,学习成...
    河仙姑阅读 164评论 2 1
  • 跑得像袋鼠 喵。 这张是抓拍,却觉得比正儿八经拍好看,所以有时候事情远没有你想象的那么糟糕啦。
    豆沫不好喝阅读 290评论 0 0
  • 文/2323 人这一生, 赤身裸体的来,赤身裸体的走。 这中间,会经过很多地方, 其中有一个地方,叫做 医院。 如...
    王2323阅读 204评论 0 0