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;
}
}

浙公网安备 33010602011771号