码迷,mamicode.com
首页 > 其他好文 > 详细

双向链表的简单实现

时间:2018-04-12 23:58:02      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:tno   integer   this   blog   ||   exception   throw   简单   void   

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

双向链表的简单实现

标签:tno   integer   this   blog   ||   exception   throw   简单   void   

原文地址:https://www.cnblogs.com/jesh/p/8811269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!