83. 删除排序链表中的重复元素
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.
删除排序链表中的重复元素。
时间O(n)
空间O(1)
思路:
每次去看一下当前节点和下一个节点的val是否相同,如是,则跳过下一个节点。
注意1 - 1 - 1这样的case怎么处理。当满足if的条件的时候,一定要写else。
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==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;
}
}

浙公网安备 33010602011771号