java 自己实现 队列 demo (链表存储)

Java

2017-07-06

161

0

技术:java8

运行环境:IDEA 15.2 + jdk8 + windows 10

demo功能:java 自己实现 队列 demo (链表存储)

源代码

http://git.oschina.net/youlixishi/demo-world/blob/master/src/algorithm/binary-search/src/main/java/com/demoworld/JLinkedListQueue.java

public class JLinkedListQueue implements IQueue {
    public JLinkedListQueue() {
        tail = null;
        head = null;
    }

    @Override
    public void push(int n) {
        JLinkedListStackNode node = new JLinkedListStackNode();
        node.value = n;
        if (this.isEmpty()) {//添加第一个元素
            tail = node;
            head = node;
            return;
        }
        if (head == tail) {
            head.next = node;
            tail = node;
            return;
        }
        tail.next = node;
        tail = node;
    }

    @Override
    public int pop() {
        if (this.isEmpty()) {
            return -1;//为了测试, 在push时 不要push -1
        }
        int n = head.value;
        head = head.next;
        if (head == null) {
            tail = null;
        }
        return n;
    }

    @Override
    public boolean isEmpty() {
        return (tail == null && head == null);
    }

    public JLinkedListStackNode tail;
    public JLinkedListStackNode head;

    class JLinkedListStackNode {
        public JLinkedListStackNode() {
            next = null;
        }

        public JLinkedListStackNode next;
        public int value;
    }
}

测试类

http://git.oschina.net/youlixishi/demo-world/blob/master/src/algorithm/binary-search/src/main/java/com/demoworld/JLinkedListQueueTest.java

public class JLinkedListQueueTest {
    //正常的 push pop
    @Test
    public void test1() {
        JLinkedListQueue j = new JLinkedListQueue();
        for (int i = 1; i <= 2; i++) {
            j.push(i);
        }

        while (!j.isEmpty()) {
            System.out.println(j.pop());
        }
    }

    //超过最长长度
    @Test
    public void test2() {
        JLinkedListQueue j = new JLinkedListQueue();
        for (int i = 1; i <= 10; i++) {
            j.push(i);
            if (i == 5) {
                System.out.println(j.pop());
            }
        }

        while (!j.isEmpty()) {
            System.out.println(j.pop());
        }
    }

    //push pop混合操作
    @Test
    public void test3() {
        JLinkedListQueue j = new JLinkedListQueue();
        for (int i = 1; i <= 10; i++) {
            j.push(i);
            if (i == 5) {
                System.out.println(j.pop());
                j.push(12);
            }
        }

        while (!j.isEmpty()) {
            System.out.println(j.pop());
        }
    }
}

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think