目录
- 一、题目
- 二、思路
- 2.1 解题思路
- 2.2 代码尝试
- 2.3 疑难问题
- 2.4 AI复盘
- 三、解法
- 四、收获
- 4.1 心得
- 4.2 举一反三
一、题目

二、思路
2.1 解题思路
2.2 代码尝试
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* deleteDuplicates(ListNode* head) {//先存储头结点ListNode* pre=head;pre->next=head;ListNode* p=head;ListNode* tem=head;//p节点用于遍历while(p->next!=nullptr){if(p->next!=p){p=p->next;}else{//temp来存储当前的值tem=p;while(p->next==p){p=p->next;}tem->next=p->next;}}return pre->next;}
};
2.3 疑难问题
2.4 AI复盘
你的代码有一些逻辑错误和冗余的部分。首先,pre->next=head 这一行是不必要的,因为 pre 已经指向 head,不需要再将其 next 指向 head。其次,你在删除重复节点时的逻辑也有问题,特别是 if(p->next!=p) 这一行,它没有正确判断节点值是否相等。
我们可以通过以下步骤来优化代码:
删除冗余代码:去掉不必要的 pre->next=head。
修正逻辑错误:正确判断节点值是否相等,并删除重复节点。
简化代码:使用更简洁的方式遍历链表并删除重复节点。
三、解法
class Solution {
public:ListNode* deleteDuplicates(ListNode* head) {if (!head) {return head;}ListNode* dummy = new ListNode(0, head);ListNode* cur = dummy;while (cur->next && cur->next->next) {if (cur->next->val == cur->next->next->val) {int x = cur->next->val;while (cur->next && cur->next->val == x) {cur->next = cur->next->next;}}else {cur = cur->next;}}return dummy->next;}
};作者:力扣官方题解
链接:https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/solutions/678122/shan-chu-pai-xu-lian-biao-zhong-de-zhong-oayn/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
四、收获
4.1 心得
用了一个int x来记录已经重复的值,这样能够把所有和该值重复的元素都删掉
4.2 举一反三
存储链表头

头上面是头发hair,这还挺好记的【狗头】

