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 6
s 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.