题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
解答:
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode h=head;
ListNode temp=h.next;
while(temp!=null){
if(temp.val==h.val){
h.next=temp.next;
}
else{
h=temp;
}
temp=temp.next;
}
return head;
}
}
题目比较简单,去除有序链表中的重复项,只需要比较新节点和前一个节点是否相同,如果相同直接删除即可。在链表不为空的情况下,第一个节点是不可能会被删除的,所以不需要在第一个节点之前创建一个节点,直接从第二个节点开始比较即可。注意对if(head==null||head.next==null)
的处理。