LeetCode 83.Remove Duplicates from Sorted List
LeetCode 83.Remove Duplicates from Sorted List (删除排序链表中的重复元素)
题目
链接
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
问题描述
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。
示例
输入:head = [1,1,2]
输出:[1,2]
思路
快慢指针,遍历一遍就行了,如果值相同,那么去除一个结点,如果不同,那么结点向后移动一位。
复杂度分析
时间复杂度 O(n)
空间复杂度 O(1)
代码
Java
public ListNode deleteDuplicates(ListNode head) {
if(head == null){
return null;
}
ListNode fast = head;
ListNode slow = head;
while (fast!=null){
if(fast.val != slow.val){
slow.next = fast;
slow = slow.next;
}
fast = fast.next;
}
slow.next = null;
return head;
}