我正在处理此Leetcode问题https://leetcode.com/problems/odd-even-linked-list/。
我已经尝试使用调试工具调试该程序,并在代码中找到该错误,但我不太了解该错误,也不知道如何解决该错误。该错误来自以下行:odd_head.next = even_head
谢谢你的帮助!
问题是:
给定一个单链表,将所有奇数节点组合在一起,然后是偶数节点。请注意,这里我们谈论的是节点号,而不是节点中的值。
For example:
Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULL
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
def oddEvenList(self, head):
odd_head = head
even_head = head.next
while(odd_head.next and odd_head.next.next):
temp = odd_head.next.next
odd_head.next = temp
odd_head = temp
odd_head.next = even_head # BUG ON THIS LINE
while(even_head.next and even_head.next.next):
temp = even_head.next.next
even_head.next = temp
even_head = temp
return odd_head
最佳答案
考虑以下列表:2->1->3->5->6->4->7->NULL
当代码到达时:
odd_head.next = even_head
链接将是:
2->3
3->6
6->7
7->NULL
1->3
5->6
4->7
even_head.next
将是3
even_head.next.next
将是6
而不是5
(这是错误的。)原因是在第一个while循环中更改了链接!因此,从这里开始一切都变得错误。
在许多可能的解决方案中,有一个简单的解决方案:
def oddEvenList(self, head):
if not head:
return head
odd_head = head
even_head_copy = even_head = head.next
while odd_head and even_head and even_head.next:
odd_head.next = even_head.next
odd_head = odd_head.next
even_head.next = odd_head.next
even_head = even_head.next
odd_head.next = even_head_copy
return head
关于python - (Python)单链表-Leetcode,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58300589/