[B] [C] [D]
Given a head pointer to a one-way linked list and the value of a node to delete, define a function to delete that node.
Returns the head node of the deleted list.
Note: this question has been changed from the original question
Example 1:
Input: head = [4,5,1,9], val = 5 Output: [4,1,9]Copy the code
Example 2:
Input: head = [4,5,1,9], val = 1 Output: [4,5,9]Copy the code
Description:
- They make sure that the values of the nodes in the list are different
- If you’re using C or C++, you don’t
free
或delete
The node is deleted
The answer is as follows:
- Because the node being removed may be a head node, you need to create a virtual head node, vHEAD, to facilitate the return of the result value
- Define two Pointers, pre to vhead and Next to head
- When next is not empty, the list is iterated
- If next.val = val, next points to the node to be deleted. Modify the pointer to next.next to delete the node
- Finally, return to vhead.next
The animation is shown below:
The code is as follows:
Var deleteNode = function(head, val) {var deleteNode = function(head, val) {let vhead = new ListNode(0), pre = vhead; Vhead. Next = head; While (head){// if head. Val =val, If (head.val===val){pre.next = head.next; return vhead.next; } pre = pre.next; head = head.next; }};Copy the code
At this point we are done with Leetcode – finger Offer 18- removing nodes from the linked list
If you have any questions or suggestions, please leave a comment!