How to delete the node of a linked list in LeetCode
This article is to share with you about how to delete linked list nodes in LeetCode, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Given the header pointer of the unidirectional linked list and the value of a node to be deleted, define a function to delete the node.
Returns the header node of the deleted linked list.
Example 1: input: head = [4Magne 5je 1je 9], val = 5 output: [4jre 1je 9] explanation: given the second node in your linked list with a value of 5, then after calling your function, the linked list should become 4-> 1-> 9. Example 2: input: head = [4Magne 5dint 1je 9], val = 1 output: [4Magne 5je 9] explanation: given the third node in your linked list with a value of 1, then after calling your function, the linked list should become 4-> 5-> 9. Description: title ensures that the values of nodes in the linked list are different. If you use C or C++ language, you do not need the node idea in which free or delete is deleted.
Special case handling: when the header node head should be deleted, you can directly return head.next.
Initialization: pre = head, cur = head.next.
Positioning node: jumps out when the cur is empty or the cur node value is equal to val.
Save the current node index, which is pre = cur.
Traverse the next section, that is, cur = cur.next.
Delete a node: if the cur points to a node, execute pre.next = cur.next. (if cur points to nullnull, the linked list does not contain nodes with the value val.
Return value: return the header node head of the linked list.
Code / * Definition for singly-linked list. * public class ListNode {* int val; * ListNode next; * ListNode (int x) {val = x;} * / class Solution {public ListNode deleteNode (ListNode head, int val) {if (head.val = = val) {return head.next;} ListNode pre = head, cur = head.next While (cur! = null & & cur.val! = val) {pre = cur; cur = cur.next;} if (cur! = null) {pre.next = cur.next;} return head;}}
The above is how to delete linked list nodes in LeetCode. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.