83. 删除排序链表中的重复元素

这里和数组去重不同,数组去重是先让slow前进再给slow赋值,链表是先给slow赋值,再让slow前进一格。
2.gif

  1. ListNode deleteDuplicates(ListNode head) {
  2. if (head == null) return null;
  3. ListNode slow = head, fast = head;
  4. while (fast != null) {
  5. if (fast.val != slow.val) {
  6. // nums[slow] = nums[fast];
  7. slow.next = fast;
  8. // slow++;
  9. slow = slow.next;
  10. }
  11. // fast++
  12. fast = fast.next;
  13. }
  14. // 断开与后面重复元素的连接
  15. slow.next = null;
  16. return head;
  17. }