LeetCode刷题(179)~删除链表的节点【常规|递归】

    科技2022-07-14  106

    题目描述

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

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

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

    示例 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 被删除的节点

    解答 By 海轰

    提交代码

    ListNode* deleteNode(ListNode* head, int val) { ListNode* ans=head; ListNode* pre=head; if(head->val==val) return head->next; while(head->next!=NULL&&head->val!=val){ pre=head; head=head->next; } pre->next=head->next; return ans; }

    运行结果 提交代码(递归)

    ListNode* deleteNode(ListNode* head, int val) { if(!head) return head; if(head->val==val) return head->next; head->next=deleteNode(head->next,val); return head; }

    运行结果 提交代码(新建一个头节点)

    ListNode* deleteNode(ListNode* head, int val) { ListNode* h=new ListNode(val-1); h->next=head; head=h; ListNode* pre=head; while(h->next!=NULL && h->val!=val){ pre=h; h=h->next; } pre->next=h->next; return head->next; }

    运行结果

    题目来源

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof

    海轰Pro 认证博客专家 C/C 微信小程序 微信小程序:「海轰Pro」微信公众号:「海轰Pro」知乎:「海轰Pro」微博:「海轰Pro」
    Processed: 0.015, SQL: 8