[LeetCode] 83. 删除排序链表中的重复元素(Remove Duplicates from Sorted List)

本文已收录于 LeetCode刷题 系列,共计 28 篇,本篇是第 8 篇

本文已收录到:LeetCode刷题 专题

[title]题目[/title]

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2
示例 2:

输入: 1->1->2->3->3
输出: 1->2->3

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

[title]视频讲解[/title]

[bilibili cid=”” page=”1″]497649929[/bilibili]

 

[title]代码[/title]

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* deleteDuplicates(ListNode* head) {
  12. ListNode* cur = head;
  13. while (cur->next != nullptr && cur != nullptr)
  14. {
  15. if (cur->val == cur->next->val)
  16. {
  17. cur->next = cur->next->next;
  18. }
  19. else
  20. {
  21. cur = cur->next;
  22. }
  23. }
  24. return head;
  25. }
  26. };
/**
 * 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* cur = head;
        
        while (cur->next != nullptr && cur != nullptr)
        {
            if (cur->val == cur->next->val)
            {
                cur->next = cur->next->next;
            }
            else
            {
                cur = cur->next;
            }
        }
        return head;
    }
};

 

作者: 高志远

高志远,24岁,男生

发表评论

邮箱地址不会被公开。