CodexBloom - Programming Q&A Platform

advanced patterns in Merge Sort with Linked Lists - Infinite Loop guide in Python

πŸ‘€ Views: 261 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-08
python algorithms linked-list Python

I'm refactoring my project and I'm testing a new approach and I'm currently implementing a merge sort algorithm for a linked list in Python, but I'm working with an unexpected infinite loop when trying to merge two sorted halves. I believe I've correctly split the linked list, but when I attempt to merge them back together, it seems to get exploring. Here’s the code I have so far: ```python class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def merge_sort(head): if not head or not head.next: return head middle = get_middle(head) next_to_middle = middle.next middle.next = None left = merge_sort(head) right = merge_sort(next_to_middle) return merge(left, right) def get_middle(head): if head is None: return head slow = head fast = head while fast.next and fast.next.next: slow = slow.next fast = fast.next.next return slow def merge(left, right): if not left: return right if not right: return left if left.value <= right.value: result = left result.next = merge(left.next, right) else: result = right result.next = merge(left, right.next) return result ``` I've confirmed that the `get_middle` function is working correctly since it appears to split the linked list properly. However, when I call the `merge` function, it enters an infinite loop in the recursive calls, particularly on the line where I recursively call `merge(left.next, right)`. At first, I thought it might be due to incorrect handling of the `next` pointers, but I’ve double-checked and they seem accurate. I’m using Python 3.9, and I believe my logic for merging nodes is sound, but I need to seem to pinpoint where the logic fails. Is there a common scenario in merging linked lists that could cause this infinite loop, or do I need to restructure my merge function? I’d appreciate any insights or debugging tips to resolve this scenario. Could this be a known issue? This is part of a larger microservice I'm building.