LeetCode Notes: Delete the Node of the Linked List

Question

Given the head pointer of the singly linked list and the value of a node to be deleted, define a function to delete the node.

Return the head node of the deleted linked list.

Note: This question has been changed compared to the original question

Example 1:

Input: head = [4,5,1,9], val = 5

Output: [4,1,9]

Explanation: Given the second node with a value of 5 in your linked list, after calling your function, the linked list should become 4 -> 1 -> 9.

Example 2:

Input: head = [4,5,1,9], val = 1

Output: [4,5,9]

Explanation: Given the third node with a value of 1 in your linked list, after calling your function, the linked list should become 4 -> 5 -> 9.

Description:

  • The question guarantees that the values of the nodes in the linked list are different from each other
  • If you use C or C++ language, you don’t need the node where free or delete is deleted

Solution

Analysis:

  1. Copy the linked list
  2. Traverse the entire linked list. If the head node is the node that needs to be deleted, just return to the next node. If not, verify that the value of the next node is a matching value. Once the value is matched, point the next node pointer down The next node, to achieve the purpose of deleting the next node

Code:

/**
  * Definition for singly-linked list.
  * function ListNode(val) {
  * this.val = val;
  * this.next = null;
  *}
  */
/**
  * @param {ListNode} head
  * @param {number} val
  * @return {ListNode}
  */
var deleteNode = function(head, val) {
     let headCopy = head
     while(head){
         // The first value is the matching value
         if(head.val === val){
             headCopy = head.next
             break
         }
         //If the value is matched, the pointer of the linked list will be changed
         else if(head.next && head.next.val === val){
             head.next = head.next.next
             break
         }
         head = head.next
     }

     return headCopy
};

Reference

Comments