这道题很简单属于一遍ac题,放两个指针,一个在前,一个在后,只要他们俩值不同,就连起来,不管中间有什么。。。
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null)return head;
if(head.next==null)return head;
ListNode first = head;
ListNode second = head.next;
while(second!=null){
if(first.val==second.val){
second = second.next;
}else{
first.next = second;
first = second;
second = first.next;
}
}
first.next = second;
return head;
}
}
本文介绍了一种简单的方法来删除链表中的重复元素。通过使用两个指针,一个在前一个在后,当发现重复元素时直接跳过,直至链表遍历完成。这种方法时间复杂度为O(n),空间复杂度为O(1)。
723

被折叠的 条评论
为什么被折叠?



