I’m working on a method to merge two sorted linked lists in Python. I encountered an issue when severing the link between nodes. Here’s my code:
<code>class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
values = []
current = self
while current:
values.append(current.val)
current = current.next
return str(values)
def __repr__(self) -> str:
return str(self)
</code>
<code>class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
values = []
current = self
while current:
values.append(current.val)
current = current.next
return str(values)
def __repr__(self) -> str:
return str(self)
</code>
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
values = []
current = self
while current:
values.append(current.val)
current = current.next
return str(values)
def __repr__(self) -> str:
return str(self)
<code>class Solution:
def mergeTwoLists(self, list1: ListNode, list2: ListNode):
self.res = ListNode(0)
self.tail = self.res
self.list1 = list1
self.list2 = list2
if list1 and list2:
if list1.val <= list2.val:
node = list1
self.list1 = self.list1.next
node.next = None
else:
node = list2
self.list2 = self.list2.next
node.next = None
self.tail.next = node
self.tail = node
if self.list1:
self.tail.next = self.list1
if self.list2:
self.tail.next = self.list2
return self.res.next
</code>
<code>class Solution:
def mergeTwoLists(self, list1: ListNode, list2: ListNode):
self.res = ListNode(0)
self.tail = self.res
self.list1 = list1
self.list2 = list2
if list1 and list2:
if list1.val <= list2.val:
node = list1
self.list1 = self.list1.next
node.next = None
else:
node = list2
self.list2 = self.list2.next
node.next = None
self.tail.next = node
self.tail = node
if self.list1:
self.tail.next = self.list1
if self.list2:
self.tail.next = self.list2
return self.res.next
</code>
class Solution:
def mergeTwoLists(self, list1: ListNode, list2: ListNode):
self.res = ListNode(0)
self.tail = self.res
self.list1 = list1
self.list2 = list2
if list1 and list2:
if list1.val <= list2.val:
node = list1
self.list1 = self.list1.next
node.next = None
else:
node = list2
self.list2 = self.list2.next
node.next = None
self.tail.next = node
self.tail = node
if self.list1:
self.tail.next = self.list1
if self.list2:
self.tail.next = self.list2
return self.res.next
list1
is initially [1, 2, 3]
list2
is initially [1, 3, 4]
because 1 <= 1
, the first condition if list1.val <= list2.val
is evaluated
after self.list1 = self.list1.next
, self.list1
points to [2, 3]
.
However, when I set node.next = None
, it seems to affect self.list1
, making it [1]
.
Why does node.next = None
affect self.list1
even though self.list1
has been reinitialized? How can I fix this issue?