83. Remove Duplicates from Sorted List

链表中相邻的重复的数字只保留一个

Example 1:

Input: 1->1->2
Output: 1->2
Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

只要一次遍历如果某个结点值和前一个结点值相同删掉即可

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head==NULL){return head;}
        ListNode *a, *b, *temp;
        a = head;
        while(a!=NULL && a->next!=NULL){
            b = a->next;
            if(a->val==b->val){
                a->next=b->next;
                //注释部分是用来删除空间的
                // delete b;
            }else{
                a=b;
            }
        }
        return head;
    }
};

 

posted @ 2019-03-07 07:49  茫茫碧落  阅读(63)  评论(0编辑  收藏  举报