image.png

指针法:

  1. class Solution {
  2. public static ListNode deleteDuplicates(ListNode head) {
  3. //处理边界情况:空链表或单节点
  4. if(head==null || head.next == null)
  5. return head;
  6. ListNode dummy = new ListNode(-1);
  7. dummy.next = head;
  8. ListNode thisNode = dummy;
  9. ListNode nextNode = head;
  10. //判断新的nextNode是否唯一:由于每次新的nextNode都是跳过了重复节点而来的,因此每个nextNode不会与前面的节点相同
  11. while(nextNode.next != null ){
  12. //若nextNode唯一,链接nextNode并更新thisNode和nextNode,新的thisNode的指向为这个nextNode的默认指向
  13. if(nextNode.val != nextNode.next.val){
  14. thisNode.next = nextNode;
  15. thisNode = thisNode.next;
  16. nextNode = nextNode.next;
  17. }
  18. //若不唯一,寻找重复节点之后的下一个节点
  19. else{
  20. while(nextNode.next != null && nextNode.val == nextNode.next.val) {
  21. nextNode = nextNode.next;
  22. }
  23. //若重复节点末端还有下一个节点,就将nextNode更新,开始新一轮判断
  24. if(nextNode.next != null){
  25. nextNode = nextNode.next;
  26. }
  27. //若重复节点末端没有下一个节点了,直接返回,此时thisNode不用再指向任何节点。
  28. else{
  29. if(thisNode == dummy)
  30. return null; //由于Leetcode允许返回null值(IDEA不允许),且要求输入[1,1,1]返回空链表,因此这里返回null
  31. thisNode.next = null;
  32. return dummy.next;
  33. }
  34. }
  35. }
  36. thisNode.next = nextNode;
  37. return dummy.next;
  38. }
  39. }

递归法:

image.png
递归函数作用是求每个节点的“可用节点”,如果该节点符合要求(即是唯一的),返回该节点自身,如果不然,进入下一递归求得该节点后面的“可用节点”。
而对于重复的节点,会直接跳到最尾端的那个节点,因此判断节点是否唯一,只需要看这个节点是否还有后续节点以及两者值是否相等;如果有且相等,又会跳到重复的这些节点的尾端。

  1. class Solution {
  2. public ListNode deleteDuplicates(ListNode head) {
  3. if (head == null) return null;
  4. if (head.next != null && head.val == head.next.val) { //如果下一节点next还有值,且这个下一节点和本节点相同,就把本节点挪到最尾的相等节点,然后继续判断下一不相等的节点;
  5. while (head.next != null && head.val == head.next.val) {
  6. head = head.next;
  7. }
  8. return deleteDuplicates(head.next);
  9. } else { //如果不然,求本节点的下一输出节点
  10. head.next = deleteDuplicates(head.next);
  11. }
  12. return head;
  13. }
  14. }