LeetCode 面试题18. 删除链表的节点

题目链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/

给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。

返回删除后的链表的头节点。

注意:此题对比原题有改动

示例 1:

输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:

输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
 

说明:

题目保证链表中节点的值互不相同
若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 
 9 struct ListNode* deleteNode(struct ListNode* head, int val){
10     if(head==NULL) return head;
11     if(head->next==NULL){
12         if(head->val==val) return NULL;
13         return head;
14     }
15     struct ListNode *pre=head,*q=pre->next;
16     if(head->val==val) return head->next;
17     while(q){
18         if(q->val==val){
19             pre->next=q->next;
20             free(q);
21             return head;
22         }else{
23             pre->next=q;
24             pre=q;
25             q=q->next;
26         }
27     }
28     return head;
29 }

猜你喜欢

转载自www.cnblogs.com/shixinzei/p/12374785.html