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
.
public ListNode deleteDuplicates(ListNode head) {
if(head==null){
return head;
}
int current=head.val;
ListNode node=head;
while(node.next!=null){
while(node.next!=null&&node.next.val==current){
node.next=node.next.next;
}
if(node.next!=null){
node=node.next;
current=node.val;
}
}
return head;
}
注意:为什么循环是用node.next循环,来判断node.next是否等于currentValue呢?因为只有在指针指向 重复结点的前一个结点 时,才能使用node.next=node.next.next来跳过重复结点。如果指针指向的是 重复结点,那么就没法删除重复结点。(有人说用node.val=node.next.val; node.next=node.next.next,可以把 重复结点 赋值为 重复结点的下一个结点,然后再跳过。但是这种方法只适用于重复结点 存在下一个结点 的情形,如果重复结点是链表的最后一个结点 就没有办法了,使用node=null没有用,必须要把重复结点的 上一个结点的next设为null。)
大神的解法跟我差不多,感觉很简洁。
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode list = head;
while(list != null) {
if (list.next == null) {
break;
}
if (list.val == list.next.val) {
list.next = list.next.next;
} else {
list = list.next;
}
}
return head;
}
}
Solution
Straight-Forward Approach [Accepted]
Algorithm
因为链表已经被排序,那么我们可以根据 某个结点的值 是否等于 它的下一个结点的值,来得出该结点是不是重复结点。
Java
public ListNode deleteDuplicates(ListNode head) { ListNode current = head; while (current != null && current.next != null) { if (current.next.val == current.val) { current.next = current.next.next; } else { current = current.next; } } return head; }
Complexity Analysis
The total run time is O(n), where n is the number of nodes in the list.
Space complexity is O(1) since no additional space is used.