给定一个排序链表,删除所有重复的元素使得每个元素只留下一个。
案例:
给定 1->1->2,返回 1->2
给定 1->1->2->3->3,返回 1->2->3
详见:https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
Java实现:
递归实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head!=null&&head.next==null){
return head;
}
ListNode tmp=head;
ListNode next=deleteDuplicates(head.next);
if(next!=null){
if(tmp.val==next.val){
tmp.next=next.next;
}
}
return head;
}
}
非递归实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur=head;
while(cur!=null){
while(cur.next!=null&&cur.val==cur.next.val){
cur.next=cur.next.next;
}
cur=cur.next;
}
return head;
}
}