• 设置虚拟头结点,用于记录最终返回结果;
  • 定义pre记录不重复节点,cur用于判断当前节点是否重复;
  • 如果出现重复节点,cur指向当前重复节点的最后一个;
  • pre下一节点指向非重复节点(当前重复节点最后一个的下一个节点);
  • 如果当前节点不重复,保留当前节点;
  • 遍历结束,返回最终结果。
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead) {
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = pHead;
        ListNode* pre = dummyHead;
        ListNode* cur = pHead;
        while (cur != NULL) {
            if (cur->next != NULL && cur->val == cur->next->val) {
                while (cur->next != NULL && cur->val == cur->next->val) {
                    cur = cur->next;
                }
                pre->next = cur->next;
                cur = cur->next;
            }
            else {
                pre = pre->next;
                cur = cur->next;
            }
        }
        return dummyHead->next;
    }
};