[Leetcode]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 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode deleteDuplicates(ListNode head) { 11 if (head==null||head.next==null) 12 return head; 13 head.next = deleteDuplicates(head.next); 14 return head.val==head.next.val? head.next:head; 15 } 16 }