Loading

LeetCode 83 删除排序链表中的重复元素

LeetCode83 删除排序链表中的重复元素

题目描述

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

样例

输入: 1->1->2
输出: 1->2
输入: 1->1->2->3->3
输出: 1->2->3

算法分析

时间复杂度

\(O(n)\)

Java代码

/**
 * 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 first = head;
        while(first!=null){
            if(first.next != null && first.val == first.next.val) first.next = first.next.next;
            else first = first.next;
        }

        return head;
    }
}
posted @ 2020-11-20 13:25  想用包子换论文  阅读(107)  评论(0)    收藏  举报