首页 > 代码库 > 83. 移除已排序链表中重复的节点 Remove Duplicates from Sorted List

83. 移除已排序链表中重复的节点 Remove Duplicates from Sorted List


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

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

移除单链表中重复的节点

  1. public class Solution {
  2. public ListNode DeleteDuplicates(ListNode head) {
  3. if (head == null)
  4. {
  5. return null;
  6. }
  7. ListNode node = head;
  8. ListNode nextNode = null;
  9. while (node.next != null)
  10. {
  11. if (node.val == node.next.val)
  12. {
  13. nextNode = node.next;
  14. while (nextNode.val == node.val)
  15. {
  16. if (nextNode.next == null)
  17. {
  18. node.next = null;
  19. return head;
  20. }
  21. else
  22. {
  23. nextNode = nextNode.next;
  24. }
  25. }
  26. node.next = nextNode;
  27. node = nextNode;
  28. }
  29. else
  30. {
  31. node = node.next;
  32. }
  33. }
  34. return head;
  35. }
  36. }


  1. public class Solution {
  2. if (head == null) return head;
  3. ListNode node = head;
  4. while (node.next != null)
  5. {
  6. if (node.val == node.next.val)
  7. {
  8. node.next = node.next.next;
  9. }
  10. else
  11. {
  12. node = node.next;
  13. }
  14. }
  15. return head;
  16. }
  17. }

大牛的递归版本

https://discuss.leetcode.com/topic/14775/3-line-java-recursive-solution



来自为知笔记(Wiz)


83. 移除已排序链表中重复的节点 Remove Duplicates from Sorted List