将第一个节点插入空的双向链表[如何]

时间:2011-03-14 23:24:58

标签: java linked-list

这是之前post的后续内容。我现在正在研究如何将第一个节点插入空的双向链表。起初看起来有点棘手......我会很感激我的addFirst方法缺少什么

...
public DLL()
{
    first = null ;
    last = null ;
}

...
DLL myList = new DLL() ;
DLLNode A = new DLLNode("Hello", null, null) ;
...

myList.addFirst(A) ;

...
public void addFirst(DLLNode v)
{
    v.pred = first ;
    v.succ = last ; 
}

[编辑]

typo.pl提出的解决方案:

public void addFirst(DLLNode v)
{
    v.pred = first ;
    v.succ = last ;
    first = v ;
    last = v ;
}

3 个答案:

答案 0 :(得分:1)

您只更新了节点的信息。

现在您需要更新DLL的信息,以了解列表中的第一个/最后一个节点是什么。当您将一个节点添加到空列表时,它很容易更新。第一个节点只有一个选择,最后一个节点只有一个选择。

答案 1 :(得分:0)

你可以做那样的事情

public void addFirst(DLLNode v){

    v.pred = null ; //v will be first node so its pred. is null
    v.succ = first; //v successor is the old first node

    if (first != null)
        first.pred = v; //the first pred. is the new node

    first  = v;     //v is now the first node in the linked list

    //if that was the first node to add , update the last pointer                    
    if (last == null)
       last = v;
}

您也可以使用Sentinel nodes

答案 2 :(得分:0)

您可以通过假装使用循环链接列表来实际改进:

public class DLLNode {
    Object contents;
    DLLNode next, prev;
}

public class DLL extends DLLNode {
    public DLL() {
        // next and prev are the first and last entry
        // but they are set to this to indicate an empty list
        next = prev = this;
    }
    public void push(DLLNode v) {
        v.next = this;
        v.prev = this.next;
        this.next.prev = v;
        this.next = v;
    }
    public void shift(DLLNode v) {
        v.prev = this;
        v.next = this.prev;
        this.prev.next = v;
        this.prev = v;
    }
    public DLLNode pop() {
        return this.remove(this.next);
    }
    public DLLNode unshift() {
        return this.remove(this.prev);
    }
    public DLLNode remove(DLLNode v) {
        if (v == this) throw new IllegalArgumentException();
        v.next.prev = v.prev;
        v.prev.next = v.next;
        v.next = null;
        v.prev = null;
        return v;
    }
}

注意即使列表为空,push如何工作:this.next与this相同,this.next.prev与this.prev相同。