【Lintcode】112. Remove Duplicates from Sorted List

题目地址:

https://www.lintcode.com/problem/remove-duplicates-from-sorted-list/description

给定一个有序链表,要求删除出现多于一次的元素,也即相同元素只剩一个。代码如下:

public class Solution2 {
    /**
     * @param head: head is the head of the linked list
     * @return: head of linked list
     */
    public ListNode deleteDuplicates(ListNode head) {
        // write your code here
        ListNode dummy = new ListNode(0), prev = dummy;
        dummy.next = head;
        ListNode cur = head;
        while (cur != null) {
        	// 越过重复元素,使得cur指向重复元素中最后一个(如果不重复那就指向唯一的那个)
            while (cur.next != null && cur.next.val == cur.val) {
                cur = cur.next;
            }
            // 将那个元素连到prev后面,然后同时移动两个指针向后一步
            prev.next = cur;
            prev = prev.next;
            cur = cur.next;
        }
        
        return dummy.next;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值