首页 > 其他 > 详细

剑指offer-18-删除链表中的节点

时间:2020-08-05 22:02:10      阅读:86      评论:0      收藏:0      [点我收藏+]

思路:

方法一: 创建一个新链表指向链表,直接遍历链表,如果找到val后将指针直接指向下个节点

代码:

/**
 * 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* dummy=new ListNode(-1);
        dummy->next=head;
        if(!head) return head;

        ListNode* cur=dummy;
        while(cur->next)
        {
            if(cur->next->val==val) cur->next=cur->next->next;
            else cur=cur->next;
        }
        return dummy->next;
    }
}

方法二:递归的思想

/**
 * 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) {
        //递归的思想
        if(!head) return head;
        //要删除头结点
        if(head->val==val) return head->next;
        head->next=deleteNode(head->next,val);
        return head;
    }
};
 
 

剑指offer-18-删除链表中的节点

原文:https://www.cnblogs.com/Sunshineboy1/p/13442508.html

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