LeetCode——remove-duplicates-from-sorted-list

Question

Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

Solution

判断当前节点和下一个节点是否相等,相等就跳过。

Code

/**
 * 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* pNode = head;
        while (pNode != NULL) {
            if (pNode->next != NULL && pNode->val == pNode->next->val) {
                pNode->next = pNode->next->next;
            } else
                pNode = pNode->next;
        }
        return head;
    }
};
posted @ 2017-10-31 12:09  清水汪汪  阅读(118)  评论(0编辑  收藏  举报