0

I've been trying to practice some linked list leet code questions. While I'm working on removing elements from a linked list I'm having a hard time understanding a "reference". The code is below:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        current = head

        if head == None:
            return head
        
        if current != None:
            if current.val == val:
                head = current.next

        # print("current ", current)      
        while (current.next is not None):
            if current.next.val == val:
                current.next = current.next.next
            else:
                current = current.next
         
        print("current",current)
        print("head", head)
        return head

First thing is the code above doesn't pass all the tests but that's not the question I'm having here. Given the inputs of [1,2,6,3,4,5,6] for the input linked list and the nodes to remove are nodes with a value of 6, I noticed the print(head) statement results in the correct solution:

('head', ListNode{val: 1, next: ListNode{val: 2, next: ListNode{val: 3, next: ListNode{val: 4, next: ListNode{val: 5, next: None}}}}})

But the print(current) statement results in just a single node:

('current', ListNode{val: 5, next: None})

I understand why current prints out a single node but how does the head print out the correct linked list with 6s removed? As far as I am aware, for the given inputs, current is assigned to head, so if I modify current only itself should be modified and not the head right? Obviously I'm wrong but where is the error in my logic?

One thing I did notice by playing in the python playground:

a = [1,2,3]
b = a
b.append(4)
# a = [1,2,3,4]
# b = [1,2,3,4]

c = 3
d = c
d = 4
# c = 3
# d = 4

I'm guessing python treats primitive types differently to other objects? Thank you.

Mark
  • 3,138
  • 5
  • 19
  • 36
  • 1
    Does this answer your question? [List changes unexpectedly after assignment. Why is this and how can I prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it) – jonrsharpe Jul 16 '21 at 17:05
  • What is a primive type [to you, in this context]? – Nelewout Jul 16 '21 at 17:06
  • It's not really a list I'm dealing with here but instead a Linked list object, but I guess my question is more general. – Mark Jul 16 '21 at 17:07
  • primitive types in python to me would be int, float, bool, string. I could be missing others – Mark Jul 16 '21 at 17:08

0 Answers0