当前位置:网站首页>Sword finger offer 18 Delete the node of the linked list

Sword finger offer 18 Delete the node of the linked list

2022-06-09 10:08:00 Mr Gao

The finger of the sword Offer 18. Delete the node of the linked list

Given the head pointer of one-way 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 .

Be careful : This question is different from the original one

Example 1:

Input : head = [4,5,1,9], val = 5
Output : [4,1,9]
explain : Given that the value of your list is 5 Second node of , So after calling your function , The list should be 4 -> 1 -> 9.

Example 2:

Input : head = [4,5,1,9], val = 1
Output : [4,5,9]
explain : Given that the value of your list is 1 The third node of , So after calling your function , The list should be 4 -> 5 -> 9.

This question is simple and conventional , The solution code is as follows :

/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */
 void  f(struct ListNode* p,int val){
    
     struct ListNode* pre;
     pre=p;
   
     
     p=p->next;
     while(p){
    
         if(p->val==val){
    
             break;
         }
         pre=p;
         p=p->next;
           
     }
     pre->next=p->next;
 }


struct ListNode* deleteNode(struct ListNode* head, int val){
    
 if(head==NULL) return head;
if(head->val==val){
    
         return head->next;
     }
f(head,val);
return head;
}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090927456517.html