LeetCode | 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.

题目解析:

设置两个指针p和q,当重复的时候将q向后移动,直到不重复位置,将p->next = q;然后进行下次的循环。直到退出。

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if(head == NULL)
            return head;
        ListNode *p,*q;
        p = head;
        q = head->next;

        while(q != NULL){
            if(q->val == p->val){
                ListNode *h = q->next;
                delete q;
                q = h;
                continue;
            }
            p = q;
            q = q->next;
        }
        p->next = NULL;
        return head;
    }
};




点赞