首页 > 其他 > 详细

剑指 Offer 18. 删除链表的节点

时间:2020-08-16 13:26:47      阅读:72      评论:0      收藏:0      [点我收藏+]

描述

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

tags: recursive, double pointer

思路

  1. 递归
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if(head == NULL){
            return head;
        }
        if(head->val == val){
            return head->next;  // val unique
        }
        head->next = deleteNode(head->next, val);
        return head;
    }
};
  1. 遍历
    利用val node 唯一的性质
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if(!head) return head;
        if(head->val == val) return head->next;
        ListNode* node = head;
        // find next.val == val
        while(node->next && node->next->val != val){
            node = node->next;
        }
        // shortcut val node
        if(node) node->next = node->next->next;
        return head;
    }
};

剑指 Offer 18. 删除链表的节点

原文:https://www.cnblogs.com/fengcnblogs/p/13512105.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!