🚩传送门:牛客题目
题目
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次
返回同样按升序排列的结果链表。
示例 1:
输入:head = [1,1,2] 输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3] 输出:[1,2,3]
解题思路:一次遍历
具体地,我们从指针 cur 指向链表的头节点,随后开始对链表进行遍历。
- 如果当前 cur 与 cur.next 对应的元素相同,那么我们就将 cur.next 从链表中移除;
- 否则说明链表中已经不存在其它与 cur 对应的元素相同的节点,因此可以将 cur 指向 cur.next 。
当遍历完整个链表之后,我们返回链表的头节点即可。
复杂度分析
时间复杂度: ,其中
是链表的长度。
空间复杂度:
我的代码
public ListNode deleteDuplicates(ListNode head) {
if(head==null)return head;
ListNode cur=head;
ListNode next=head.next;
while(next!=null){
//1. 如果相等删除next结点
if(cur.val==next.val){
cur.next=next.next;
next=next.next;
}else{
cur=next;
next=next.next;
}
}
return head;
}
官方代码
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return head;
ListNode cur = head;
while (cur.next != null) {
if (cur.val == cur.next.val)
cur.next = cur.next.next;
else
cur = cur.next;
}
return head;
}