1. 程式人生 > >雙向鏈表的簡單實現

雙向鏈表的簡單實現

ati ret lin else out color ringbuf main oid

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

雙向鏈表的簡單實現