categories: [Blog,Algorithm]


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

难度简单480
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 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() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public ListNode deleteDuplicates(ListNode head) {
  13. ListNode current = head;
  14. while (current != null && current.next != null) {
  15. if (current.next.val == current.val) {
  16. current.next = current.next.next;
  17. } else {
  18. current = current.next;
  19. }
  20. }
  21. return head;
  22. // 作者:LeetCode
  23. // 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/solution/shan-chu-pai-xu-lian-biao-zhong-de-zhong-fu-yuan-s/
  24. }
  25. }