Title description:
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.
Example 1:
Input: head = [4,5,1,9], val = 5
Output: [4,1,9]
Explanation: Given the second node with value 5 in your linked list, then after calling your function , The linked list should be 4 -> 1 -> 9.
Example 2:
Input: head = [4,5,1,9], val = 1
Output: [4,5,9]
Explanation: Given the third node whose value is 1 in your linked list, then after calling your function , The linked list should be 4 -> 5 -> 9.
Problem-solving ideas:
This question is simply delete the linked list, traverse the linked list and then encounter the node that needs to be deleted, just use a next
Need to pay attention to when deleting nodes is the first problem
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
ListNode*head1=head;
ListNode* m=NULL;
if(head->val == val)
{
return head->next;
}
while(head1)
{
m=head1->next;
if(m->val == val)
{
head1->next = m->next;
break;
}
head1=head1->next;
}
return head;
}
};