我的代码就像:
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} val
# @return {ListNode}
def removeElements(self, head, val):
def printLinked(head):
while head:
print head.val,"->"
head = head.next
dummy = ListNode(0)
dummy.next = head
cur = dummy
while cur and cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
printLinked(dummy.next)
print "._."
printLinked(head)
return head
我发现如果我返回dummy.next而不是head,我的代码将是正确的。 但是,我无法理解head和dummy.next之间的区别。
当我的测试用例是head = ListNode(1)时,val = 1.头部仍然是1,但是dummy.next是[]。
我很困惑,因为当测试用例是head = 1 - > 2 - > 6 - > 3 - > 4 - > 5 - >在图6中,val = 6,头部和虚设。下一个是1 - > 2 - > 3 - > 4 - > 5。我认为对我来说必定会对头脑和假人产生一些误解。任何人都能为我解释一下吗?
答案 0 :(得分:0)
根据Kendas的评论,“cur.next属性指向相同的对象头指向。当你给cur.next另一个值(cur.next == cur.next.next)时,它没有指向那个对象。然而,变量头仍指向它之前所做的同一个对象。“ 希望这会有所帮助。