For 1:
两变量,pre and cur, 如果cur->val == pre->val,就cur = cur->next 跳过。最后记得pre->next = NULL
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head) return NULL;
ListNode *pre = head, *cur = head->next;
while(cur){
if(cur && cur->val == pre->val){
cur = cur->next;
}else{
pre->next = cur;
pre = cur;
cur = cur->next;
}
}
pre->next = NULL;
return head;
}
};
For 2:
也是两变量,不过处理方式有所不同。由于head node可以被删,需要建立dummy node。
- 用cur->next->val == cur->val来比较,pre始终位于可能被删除的第一个节点之前。
- 也是用同样的if/else结构,来填充while loop。只不过比较形式不同
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head) return NULL;
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *pre = dummy, *cur = pre->next;
while(cur){
if(cur->next && cur->next->val == cur->val){
while(cur->next && cur->next->val == cur->val){
cur = cur->next;
}
pre->next = cur->next;
cur = cur->next;
}else{
//pre->next = cur;
pre = cur;
cur = cur->next;
}
}
head = dummy->next;
delete dummy;
return head;
}
};