题目
给定一个已排序的链表的头head,删除所有重复的元素,使每个元素只出现一次。返回已排序的链表。
示例
输入:head = [1,1,2]
输出:[1,2]
输入:head = [1,1,2,3,3]
输出:[1,2,3]
解决方案
方案一:双指针法
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) {
return head;
}
ListNode node = head;
ListNode slow = head, fast = head.next;
while (fast != null) {
if(fast.val != slow.val) {
slow= slow.next;
slow.val = fast.val;
}
fast = fast.next;
}
slow.next = null;
return head;
}
}
方案二:单指针遍历
也可以用一个指针遍历,如果后一个元素与前一个元素一样,就直接删掉这个元素。