0

I was doing some problems in python specifically this one:

Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node

The solution is this:

def deleteNode(linkedlist, node):
    if node.next != None:
        node.value = node.next.value
        node.next = node.next.next  
    else:
        node.value = None

I've done some Java before and the A = B with objects means A refers to B. According to this problem. Does this mean in the python expression A = B that A deep-copies B?

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
Liondancer
  • 15,721
  • 51
  • 149
  • 255
  • 3
    In Python non primitive types are always passed by reference. See: http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference – Grapsus May 15 '14 at 06:32
  • @Grapsus Because "Call by Reference" is such an overloaded term and fails to unify across types/languages, I prefer to simply use [Call by (Object) Sharing](http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing). - Using "Call by Reference" for this is a Python'ism and is *wrong* in many other language contexts. – user2864740 May 15 '14 at 06:33
  • @user2864740 Whatever floats your boat. – Grapsus May 15 '14 at 06:38
  • 1
    @Grapsus: There's no distinction between primitives and non-primitives. Everything is stored and passed around by reference, even ints. – user2357112 May 15 '14 at 06:38
  • @user2357112 Ok, I agree, everything is passed by reference. There is no primitive types, only immutable types. – Grapsus May 15 '14 at 06:46

1 Answers1

4

No. A = B works pretty much the same in Python as it does in Java. (There are a few differences in certain advanced use cases, but those aren't important here.)

This function doesn't actually delete the node. It cheats; the next node's data gets copied into this node, and the next node is deleted. As long as no one else was relying on the identity of specific nodes in the list, and as long as there is a next node, it works okay. (The else that looks like it handles the case where there is no next node is actually bugged; instead of deleting the data from the list, it replaces the data with a spurious None value.)

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 1
    The quoted problem, and its solution seem simply awful, leaving so many doors open to problems. Especially as it relies on deep-copy. – Jonathon Reinhart May 15 '14 at 06:35
  • Thank you for clearing this up! I found this problem in the cracking the code interview book and it's solution in the official github :( – Liondancer May 15 '14 at 06:41