首页 > 其他分享 >剑指 Offer 18.删除链表节点

剑指 Offer 18.删除链表节点

时间:2023-03-08 21:56:42浏览次数:52  
标签:pre head ListNode cur val Offer 18 next 链表

题目表述

 

 

 

解法

双指针法

class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
            ListNode *a = head->next;
            ListNode *b = head;
            if(head->val == val){
                head = head->next;
            }
            while(a != nullptr){
                if(a->val == val){
                    b->next = a->next;
                }
                a = a->next;
                b = b->next;
            }
            return head;
    }
};

 

参考:https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof/solution/mian-shi-ti-18-shan-chu-lian-biao-de-jie-dian-sh-2/

<1>定位节点

<2>修改引用

class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if(head->val == val) return head->next;
        ListNode *pre = head, *cur = head->next;
     //定位到cur的位置后跳出循环  while(cur != nullptr && cur->val != val) { pre = cur; cur = cur->next; }
     //修改引用 if(cur != nullptr) pre->next = cur->next; return head; } };

 

标签:pre,head,ListNode,cur,val,Offer,18,next,链表
From: https://www.cnblogs.com/zc-030/p/17196398.html

相关文章