开发者

How to get root node while deleting from singly linked list

I was wondering how this function is getting the root node while trying to delete a node from a singly linked list. I understand t开发者_Python百科he whole deletion part.

class LinkedList { 
    LinkedListNode root; 

    // Remove the nodes which contain data equal to obj 
    void deleteNode(Object obj) { 
        // special case for root 
        if( root.data.equals(obj) ) { 
            root = root.next; 
        }  
        LinkedListNode current = root; 
        // iterate through list looking for obj 
        while( current.next != null ) { 
            // match found 
            if( current.next.data.equals(obj) ) { 
                // cut out the node 
                current.next = current.next.next; 
            } 
            current = current.next; 
        }
    }
} 

private class LinkedListNode { 
    Object data; 
    LinkedListNode next; 
} 

I'm not sure why just by creating a LinkedListNode root, it refers to the root node. Clear and easy to understand help would be much appreciated.

Ff theoretically I didn't create the LinkedListNode root, could I just pass in an extra parameter to the delete function, and specify which one is the head based on its data?

LinkedListNode deleteNode(LinkedListNode head, int d) {
    LinkedListNode n = head;
    if (n.data == d) {
        return head.next; /* moved head */
    }
    while (n.next != null) {
        if (n.next.data == d) {
            n.next = n.next.next;
            return head; /* head didn’t change */
        }
        n = n.next;
    }
}


I'm not sure I understand the question...

LinkedListNode root is a private member of the class LinkedList, presumably initialized in a constructor and/or elsewhere in an AddNode function or something. Once you have the member root initialized (and referencing the root node of the list), functions like DeleteNode are allowed to use it, such as if( root.data.equals(obj) ) { root = root.next; }

I hope this helps somewhat...


It's not automatic. "root" is a class variable for the LinkedList class, which is to say that every instance of the LinkedList class has an attribute called root that is some LinkedListNode. You can use and/or reference this anywhere in the class definition.

The root node will be specified when an instance of the LinkedList class is created, in its constructor (which I'm assuming exists somewhere). If it isn't, there won't be any reference to the LinkedList you created and it will be all but useless.

To answer the second part of your question, you could write such a function but there is no need to. It would be redundant; you can just use the reference to the root node.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜