NC25 删除有序链表中重复的元素-I
描述 删除给出链表中的重复元素(链表中元素从小到大有序),使链表中的所有元素都只出现一次 例如: 给出的链表为1\to1\to21→1→2,返回1 \to 21→2. 给出的链表为1\to1\to 2 \to 3 \to 31→1→2→3→3,返回1\to 2 \to 31→2→3.
import java.util.*;
public class Solution {
public ListNode deleteDuplicates (ListNode head) {
if(head == null || head.next == null){
return head ;
}
ListNode dummy = new ListNode(0);
ListNode tail = dummy ;
while(head != null){
while(head.next != null && head.val == head.next.val){
head = head.next ;
}
tail.next = new ListNode(head.val) ;
tail = tail.next ;
head = head.next ;
}
return dummy.next ;
}
}
|