来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/

描述

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

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

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

题解

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode deleteDuplicates(ListNode head) {
  11. ListNode current = head;
  12. while (current != null && current.next != null) {
  13. if (current.val == current.next.val) {
  14. current.next = current.next.next;
  15. } else {
  16. current = current.next;
  17. }
  18. }
  19. return head;
  20. }
  21. }

复杂度分析

  • 时间复杂度:83. 删除排序链表中的重复元素(Remove Duplicates from Sorted List) - 图1
  • 空间复杂度:83. 删除排序链表中的重复元素(Remove Duplicates from Sorted List) - 图2