双向链表的简单实现

Posted jesh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了双向链表的简单实现相关的知识,希望对你有一定的参考价值。

package dataStructure;

public class DoubleLinkedList<T> {

    private final Node<T> head;
    private int count = 0;
    
    
    public DoubleLinkedList()
    {
        head = new Node<T>(null,null,null);
        head.pre = head;
        head.next = head;
    }
    
    public int size()
    {
        return count;
    }
    
    public boolean isEmpty()
    {
        return count == 0;
    }
    
    public void add(T data)
    {
        Node<T> n = new Node<T>(data, head.pre, head);
        head.pre = n;
        n.pre.next = n;
        count ++;
    
    }
    
    private Node<T> getNode(int index)
    {
        if(index < 0 || index >count)
        {
            throw new IndexOutOfBoundsException();
        }
        Node<T> tmp = head;
        if(index <= count/2)
        {
            for(int i= 0;i<index;i++)
            {
                tmp = tmp.next;
            }
        }
        else
        {
            for(int i=0;i< count-index;i++)
            {
                tmp = tmp.pre;
            }
        }
        return tmp;
    }
    
    public T get(int index)
    {
        Node<T> n = getNode(index);
        return n.data;
    }
    
    public void del(int index)
    {
        Node<T> n = getNode(index);
        n.pre.next = n.next;
        n.next.pre = n.pre;
        count--;
        
    }
    public String toString()
    {
        StringBuffer sb = new StringBuffer();
        Node<T> n = head;
        for(int i = 0;i<count+1;i++)
        {
            sb.append(n.toString()).append("-->");
            n = n.next;
        }
        return sb.toString();
    }
    private class Node<T>
    {
        T data;
        Node<T> pre;
        Node<T> next;
        public Node(T data,Node<T> pre,Node<T> next)
        {
            this.data = data;
            this.pre = pre;
            this.next = next;
        }
        
        public String toString()
        {
            return "data:"+this.data;
        }
        
    }
    
    public static void main(String[] args)
    {
        DoubleLinkedList<Integer> d = new DoubleLinkedList<>();
        System.out.println(d);
        for (int i = 0 ;i<10;i++)
        {
            d.add(i);
        }
        System.out.println(d.toString());
        System.out.println(d.get(1));
        d.del(1);
        System.out.println(d.get(1));
        System.out.println(d);
        
    }
}

参考http://www.cnblogs.com/skywang12345/p/3561803.html#a33

以上是关于双向链表的简单实现的主要内容,如果未能解决你的问题,请参考以下文章

C 双向链表的简单排序实现

双向链表的简单Java实现-sunziren

Java数据结构—— 双向链表及带傀儡节点双向链表的实现

双向链表的简单实现

数据结构——双向链表的实现

Java中双向链表的代码实现