My code is like:
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
I find the if I return dummy.next rather than head, my code will be correct. But, I cannot understand what's the difference between head and dummy.next.
When my test case is head = ListNode(1),val = 1. The head will still be 1, but the dummy.next is [].
I am quite confused, because when the test case is head = 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6, both head and dummy.next is 1-->2-->3-->4-->5. And I think there must be some misunderstand of head and dummy for me. Can any one explain it for me?
Based on Kendas's comment, "The cur.next attribute points to the same object head points to. When you give cur.next another value (cur.next == cur.next.next), it doesn't point to that object anymore. However, the variable head still points to the same object it did before." Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.