这个题和剑指上不太一样 剑指上把所有重复元素都删了 这个只保留一个
答案:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head){
if(head == nullptr) return nullptr;
ListNode* pre = head ;ListNode* cur = head->next;
while(cur != nullptr){
while(cur != nullptr && pre->val == cur->val){
cur = cur->next;
}
pre->next = cur;
pre = cur;
}
return head;
}
};
刚开始自己写的:(coding的一些细节还是要注意啊)
/**
* 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) {
if(head==nullptr) return head;
ListNode* pre=head;
ListNode* cur=head->next;
while(cur!=nullptr){
while(cur!=nullptr && pre->val==cur->val){
//不论cur->next是不是nullptr 都可以赋给前一个的指针的next
pre->next=cur->next;
cur=pre->next;//要把cur落实 while循环条件里有cur
}
pre=cur;
cur=cur->next;//感觉这里不能写cur的next 因为可能是空的 但是居然连cur->next都不能写
//pre->next = cur;
//pre = cur;改成这两句居然就能通过了 无语
}
return head;
}
};
自己的和上面那个我还是有一些想不通 找到了一个特别清楚的思路
java写的
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while(cur != null && cur.next != null) {
if(cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}
作者:guanpengchn
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/solution/hua-jie-suan-fa-83-shan-chu-pai-xu-lian-biao-zhong/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
人家怎么写的这么清楚
2021/4/15 解决了一个问题
当时一直不理解为什么单个指针就没有错误 改成两个指针就不行了
单个指针代码
/**
* 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) {
if(head==nullptr) return nullptr;
//ListNode* pre=head;
ListNode* cur=head;
while(cur!=nullptr&&cur->next!=nullptr){
if(cur->val==cur->next->val){
cur->next=cur->next->next;
}
else{
cur=cur->next;
}
}
return head;
}
};
双指针代码
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==nullptr) return nullptr;
ListNode* pre=head;
ListNode* cur=head->next;
while(pre!=nullptr&&cur!=nullptr){
if(cur->val==pre->val){
pre->next=cur->next;
//一定要写下面这句
cur=pre->next;
}
else{
pre=cur;
cur=cur->next;
}
}
return head;
}
};
双指针要注意迭代的时候两个指针都要变