[leetcode] Remove Duplicates from Sorted List


Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

tag: linked list

简单题,但要注意两点:
1. if 语句条件的判断顺序为从左到右,所以要把判断P为空放在左面先判断,然后再判断p->val == head->val
2. 在函数开始时,把head拷贝给re作为返回元素,head在操作中会被移动。当然,另一个好习惯是把head拷贝成p,然后操作p,最后返回head。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode * re = head;
        while(head != NULL){
            ListNode * p = head;
            while(p != NULL && p->val == head->val){
                p = p->next;
            head->next = p;
            head = head->next;
        }
        return re;
    }
};

Selection_008

 

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.