【Leetcode】82. Remove Duplicates from Sorted List II
Question:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
Tips:
跟83题比较,本题需要删除所有的重复数字,即只要一个数字出现重复,那么总第一个该数字开始都将被删除。
思路:
①设置一个新的头结点newHead,以及一个pre结点一个cur结点。将pre初始化为newHead,在pre之后找到第一个不重复的结点,并将其赋值给pre.next。
②递归。找到第一个不重复的结点,将它的next结点递归。
代码:
public ListNode deleteDuplicates1(ListNode head) { if (head == null || head.next == null) return head; ListNode newHead = new ListNode(-1); newHead.next = head; ListNode pre = newHead; ListNode cur = head; while (cur != null) { //找到第一个不重复的结点 while (cur.next != null && cur.val == cur.next.val) cur = cur.next; //当pre的next就是cur即两者之间没有重复数字,将pre指针后移即可。 if (pre.next == cur) { pre = cur; } else //否则 跳过cur 将pre的next设置成cur的next pre.next = cur.next; cur = cur.next; } return newHead.next; }
②:
public ListNode deleteDuplicates(ListNode head) { if (head == null) return null; if (head.next != null && head.val == head.next.val) { while (head.next != null && head.val == head.next.val) { head = head.next; } return deleteDuplicates(head.next); } else { head.next = deleteDuplicates(head.next); } return head; }