83.Remove Duplicates from Sorted List(E)
https://leetcode.com/problems/remove-duplicates-from-sorted-list/
1.Description(Easy)
Given a sorted linked list, delete all duplicates such that each element appear onlyonce.
Example
Given1->1->2
, return1->2
.
Given1->1->2->3->3
, return1->2->3
.
2.Code
Version 1: 定义一个current指向head,直接遍历剔除即可。
public static ListNode deleteDuplicates(ListNode head) {
if(head==null ||head.next==null){
return head;
}
ListNode current=head;
while(current.next!=null){
if(current.val==current.next.val){
current.next=current.next.next;
}
else{
current=current.next;
}
}
return head;
}
Version 2: 快慢指针
其实和数组去重LeetBode 26 是一模一样的,唯一的区别是把数组赋值操作变成操作指针而已:
ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;
ListNode slow = head, fast = head;
while (fast != null) {
if (fast.val != slow.val) {
// nums[slow] = nums[fast];
slow.next = fast;
// slow++;
slow = slow.next;
}
// fast++
fast = fast.next;
}
// 断开与后面重复元素的连接
slow.next = null;
return head;
}
Last updated
Was this helpful?