问各位一道 leetcode 上的题目

2015-11-03 13:30:13 +08:00
 billyzs

https://leetcode.com/problems/remove-linked-list-elements/

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

一开始用 recursion 写了个解法,碰到长一点的 input 就超时了。去看了一眼大家的 solution ,虽然每行干的啥能看懂,可和在一起就百思不得其解,好比这个:

def removeElements(self, head, val):
    dummy = cur = ListNode(0)
    dummy.next = head
    while cur and cur.next:
        if cur.next.val == val:
            cur.next = cur.next.next
        else:
            cur = cur.next
    return dummy.next

明明是操作了cur, 为什么return dummy.next返回的是正确答案呢? p2ex 上高手多,我先谢过了

3576 次点击
所在节点    Python
22 条回复
kmahyyg
2015-11-04 00:24:28 +08:00
@domty lintcode 咋样?有手机客户端吗?
chy373180
2015-11-04 09:58:22 +08:00
建议看下 python 中的拷贝

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/233222

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX