欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 83. Remove Duplicates from Sorted List

程序员文章站 2022-07-14 08:40:46
...

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.

给定一个已排序的链表,删除其中重复的结点。
思路:
LeetCode 83. Remove Duplicates from Sorted List

class Solution {
public:

    ListNode* deleteDuplicates(ListNode* head) {
        if (head == NULL) return head;

        ListNode **pp = &head;
        int preValue = (*pp)->val;
        pp = &((*pp)->next);
        while (*pp)
        {
            int value = (*pp)->val;
            if (preValue == value)
            {
                ListNode *p = *pp;
                *pp = (*pp)->next;
                delete p;
            }
            else {
                preValue = value;
                pp = &((*pp)->next);
            }
        }
        return head;
    }
};
相关标签: leetcode