Java实现双向链表(LinkList)(优雅)

发布于 2021-07-21  51 次阅读


上班摸鱼鱼 蛮简单的

LinkList类代码如下:

package com.apesblog.LinkList2;

import java.util.Iterator;

public class LinkList2<T> implements Iterable<T> {
    private int N;
    private Node head;
    private Node tail;

    private class Node {
        T item;
        Node next;
        Node pre;

        public Node(T item, Node pre, Node next) {
            this.item = item;
            this.next = next;
            this.pre = pre;
        }
    }

    public LinkList2() {
        this.head = new Node(null, null, null);
        this.tail = null;
        this.N = 0;
    }

    public T get(int i) {
        if (i < 1 || i > N) {
            throw new RuntimeException("查询位置不正确");
        }
        Node p = head;
        for (int index = 1; index <= i; index++) {
            p = p.next;
        }
        return p.item;
    }

    public void add(T t) {
        if (tail == null) {
            head.next = tail = new Node(t, head, null);
        } else {
            tail = tail.next = new Node(t, tail, null);
        }
        N++;
    }

    public void insert(int i, T t) {
        Node p = head;
        if (i < 1 || i >= N) {
            throw new RuntimeException("插入位置不正确");
        }
        for (int index = 1; index < i; index++) {
            p = p.next;
        }
        p.next = p.next.pre = new Node(t, p, p.next);
        N++;
    }

    public void delete(int i) {
        if (i < 1 || i > N) {
            throw new RuntimeException("删除位置不正确");
        }
        Node p = head;
        for (int index = 1; i < i; i++) {
            p = p.next;
        }
        p.next = p.next.next;
        p.next.pre = p.next.pre.pre;
        N--;
    }

    @Override
    public Iterator<T> iterator() {

        return new Iterator() {
            private Node p = head;

            @Override
            public boolean hasNext() {
                return p.next != null;
            }

            @Override
            public Object next() {
                p = p.next;
                return p.item;
            }

        };
    }

}

测试代码如下:

package com.apesblog.LinkList2;

public class Test {

    public static void main(String[] args) {
        LinkList2<String> l = new LinkList2<String>();
        l.add("1");
        l.add("2");
        l.add("3");
        l.add("5");
        l.add("6");
        System.out.println("获取第2个元素:" + l.get(2));

        StringBuilder str = new StringBuilder(300);
        str.append("遍历:");
        for (String s : l) {
            str.append(s + " ");
        }
        System.out.println(str);

        l.insert(4, "4");
        str.delete(0, str.length());
        str.append("插入:");
        for (String s : l) {
            str.append(s + " ");
        }
        System.out.println(str);

        str.delete(0, str.length());
        l.delete(1);
        str.append("删除:");
        for (String s : l) {
            str.append(s + " ");
        }
        System.out.println(str);
    }

}

运行结果如下: