美文网首页
LinkList (双向链表)

LinkList (双向链表)

作者: ae12 | 来源:发表于2018-09-05 17:33 被阅读27次

    Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).

    无容量限制,但是本身链表指针占用更多的空间、也需要额外的链表指针操作
    add(i) :插入操作,改变前后指针
    delete (i)
    访问,指针遍历:
    按下标访问元素—get(i)/set(i,e) 要悲剧的遍历链表将指针移动到位(如果i>数组大小的一半,会从末尾移起);
    插入、删除也需要先遍历:
    插入、删除元素时修改前后节点的指针即可,但还是要遍历部分链表的指针才能移动到下标所指的位置
    只有在链表两头的操作—add(),addFirst(),removeLast()或用iterator()上的remove()能省掉指针的移动
    添加数据
    LinkedList<String> list = new LinkedList<>();
    list.add("语文 :1");
    list.add("数学:2");
    list.add("英语:3");

    LinkedList-store.png

    插入、删除比较快,但是查找比较慢

    二、 set和get函数 {#2-_set和get函数}

    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
    

    这两个函数都调用了node函数,该函数会以O(n/2)的性能去获取一个节点,具体实现如下所示:

    Node<E> node(int index) {
        // assert isElementIndex(index);
        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }
    

    就是判断index是在前半区间还是后半区间,如果在前半区间就从head搜索,而在后半区间就从tail搜索。而不是一直从头到尾的搜索。如此设计,将节点访问的复杂度由O(n)变为O(n/2)。

    算法 实例:

    1. Intersection of Two Linked Lists
      Write a program to find the node at which the intersection of two singly linked lists begins.

    For example, the following two linked lists:

    
    A:             a1 → a2
                                ↘
                                  c1 → c2 → c3
                                ↗            
    B:     b1 → b2 → b3
    

    begin to intersect at node c1.

    暂时木有 算法

    LIn

    相关文章

      网友评论

          本文标题:LinkList (双向链表)

          本文链接:https://www.haomeiwen.com/subject/wqggwftx.html