题目表述
解法
双指针法
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