83. Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
删除链表中的重复项
给定已排序的链接列表,删除所有重复项,使每个元素只出现一次。
递归,当 head.val 与 head.next.val 相等时,return head.next;
public class RemoveDuplicatesFromSortedListII { public ListNode deleteDuplicates(ListNode head) { if (head == null) return null; return dfs(head); } public ListNode dfs(ListNode head){ if (head.next == null) return head; if (head.val == head.next.val){ return dfs(head.next); }else { head.next = dfs(head.next); return head; } } public static void main(String[] args) { RemoveDuplicatesFromSortedListII removeDuplicatesFromSortedListII = new RemoveDuplicatesFromSortedListII(); ListNode l1 = new ListNode(1); l1.next = new ListNode(1); l1.next.next = new ListNode(1); l1.next.next.next = new ListNode(2); l1.next.next.next.next = new ListNode(3); removeDuplicatesFromSortedListII.deleteDuplicates(l1); } }