原文链接: https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
英文原文
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example 1:

Input: head = [1,1,2] Output: [1,2]
Example 2:

Input: head = [1,1,2,3,3] Output: [1,2,3]
Constraints:
- The number of nodes in the list is in the range
[0, 300]
. -100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
中文题目
存在一个按升序排列的链表,给你这个链表的头节点 head
,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。
示例 1:

输入:head = [1,1,2] 输出:[1,2]
示例 2:

输入:head = [1,1,2,3,3] 输出:[1,2,3]
提示:
- 链表中节点数目在范围
[0, 300]
内 -100 <= Node.val <= 100
- 题目数据保证链表已经按升序排列
通过代码
高赞题解
思路
- 标签:链表
- 指定 cur 指针指向头部 head
- 当 cur 和 cur.next 的存在为循环结束条件,当二者有一个不存在时说明链表没有去重复的必要了
- 当 cur.val 和 cur.next.val 相等时说明需要去重,则将 cur 的下一个指针指向下一个的下一个,这样就能达到去重复的效果
- 如果不相等则 cur 移动到下一个位置继续循环
- 时间复杂度:$O(n)$
代码
[]/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode cur = head; while(cur != null && cur.next != null) { if(cur.val == cur.next.val) { cur.next = cur.next.next; } else { cur = cur.next; } } return head; } }
[]/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var deleteDuplicates = function(head) { var cur = head; while(cur && cur.next) { if(cur.val == cur.next.val) { cur.next = cur.next.next; } else { cur = cur.next; } } return head; };
画解
<,
,
,
>
想看大鹏画解更多高频面试题,欢迎阅读大鹏的 LeetBook:《画解剑指 Offer 》,O(∩_∩)O
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
342875 | 637494 | 53.8% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|
相似题目
题目 | 难度 |
---|---|
删除排序链表中的重复元素 II | 中等 |