Question
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.
Subscribe to see which companies asked this question
本题难度Easy。
【复杂度】
时间 O(N) 空间 O(1)
【思路】
两种情况:
-
cur.val==cur.next.val
,删除cur.next -
cur.val!=cur.next.val
,cur向后移一位
【附】
这题的思路我是从[LeetCode]Remove Duplicates from Sorted List II简化而来。写完后我有个疑问:第一种情况下,为什么cur不向后移动一位。然而我明白实际上cur兼有prev和cur的功能,删除了cur.next就是移动了cur。
【代码】
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
//invariant
ListNode cur=head;
while(cur!=null&&cur.next!=null){
if(cur.val==cur.next.val){
cur.next=cur.next.next;
}else
cur=cur.next;
}
//ensure
return head;
}
}