83.Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

给定一个有序数组,删除其中所有重复的元素,使每个元素只出现一次~

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

 

高票答案

wen587sort

 采用了递归的方法~

public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)return head;
        head.next = deleteDuplicates(head.next);
        return head.val == head.next.val ? head.next : head;
//A ? B :C (如果A为真执行B否则执行C),若head.val==head.next.vall,返回head.next舍弃head;否则返回head;
}

不过这个答案的下面有评论:
 I highly doubt if we should use recursion in solving linked list problems. We use it for tree because its stack space is O(logn), where n is the number of nodes. But it’s O(n) space required for linked list, which is very likely to be stack overflow. Point me out if you hold a different opinion.
翻译下:我高度怀疑在链表类问题中是否有使用递归的必要。我们在树中使用是因为树所需的栈空间为O(logn),n为节点数目;而对于链表来说,需要的栈空间为O(n),非常容易栈溢出。

我的方法

public ListNode deleteDuplicates(ListNode head) {
if(head==null)
return null;
ListNode nowNode = head;
while(true){
while (nowNode.next != null && nowNode.next.val == nowNode.val)
if (nowNode.next.next != null)
nowNode.next = nowNode.next.next;
else
nowNode.next=null;
if(nowNode.next!=null)
nowNode=nowNode.next;
else
return head;
}
}

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值