美文网首页
【leetcode】- 83.Remove Duplicates

【leetcode】- 83.Remove Duplicates

作者: 邓泽军_3679 | 来源:发表于2019-04-05 18:30 被阅读0次

1、题目描述

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

  • Example 1:

Input: 1->1->2
Output: 1->2

  • Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

2、问题描述:

  • 删除链表中重复的值。

3、问题关键:

  • 双指针,因为是排好序的,一个先走,指导前后指针值不一样的时候,将后面的指针指向的元素指向先走指针指向的元素,并移动后面的指针。

4、C++代码:

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return nullptr;
        ListNode *first = head, *second = head;
        while(first) {
            if (first->val != second->val) {//让first先走,直到走到两个位置的值不一样了。
                second->next = first;//让second指向的元素指向first指向的元素。
                second = first;//移动second指针。
            }
            first = first->next;//first向后移动一步。
        }
        second->next = nullptr;//
        return head;
    }
};

相关文章

网友评论

      本文标题:【leetcode】- 83.Remove Duplicates

      本文链接:https://www.haomeiwen.com/subject/zakciqtx.html