美文网首页
Remove Duplicates from Sorted Li

Remove Duplicates from Sorted Li

作者: stepsma | 来源:发表于2016-11-06 07:43 被阅读0次

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。

  1. 用cur->next->val == cur->val来比较,pre始终位于可能被删除的第一个节点之前。
  2. 也是用同样的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;
        
    }
};

相关文章

网友评论

      本文标题:Remove Duplicates from Sorted Li

      本文链接:https://www.haomeiwen.com/subject/dcgguttx.html