简体   繁体   中英

How can I implement append and deleteNode methods for a LinkedList implementation in Java?

I am improving my data structures skills. I am trying to implement a LinkedList from scratch. This is what I have done so far:

class Node {
    Node next = null; //reference to null
    Object data;  //value of the node

    public Node(Object d) {
        data = d;    //constructor that assigns the node's value to the node
    }

    void append(Object d) {
        Node end = new Node(d); //create the new node
        Node n = this;  

        while (n.next != null) {  //keep moving the reference until we reach null which is the reference of the last node       
            n = n.next;    
        }

        n.next = end;   //Assign the null reference to the node end which is the node to be added
    }

    Node deleteNode(Node head, Object d){
        Node n = head;    //Call the pointer to the head n;

        if (n.data == d) {  //Check if the data of the current node is same as node to be deleted
            return head.next;   //Here I got lost, I don't know why we're returning head.next
        }

        while (n.next != null) {  //as long as we have reached the last node
            if (n.next.data == d) {
                n.next = n.next.next; //I don't get this
                return head; //Why are we returning head
            }

            n = n.next;
        }

        return head;
    }
}

The problem is I don't understand the deleteNode method. I have found it in the book Cracking the Code interview. Could someone please clarify for me what is actually happening? The whole reference thing is getting me confused.

The deleteNode method seems to return the linked list. Here's what it does:

  1. If the first element of the linked list is the item that we seek (its data matches d ), then we just return the list starting from the second element ( head.next ). There's nothing linking back to that first element, so the first element is gone. Just what we wanted.
  2. Look through all nodes. They do this by looking at n.next . If its data matches d , then this node should be removed. So then let the list skip that element: Set n.next to be n.next.next (which is the element after it) rather than the element that matched d .

Normally these kinds of methods tend to return the element that was removed. Instead, this seems to return the list itself, which is represented by its head. That's why the method keeps returning head .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM