2 因此,我在这里面临着疑问。
我正在读《破解编码面试》一书。以下文字写在那儿。
假设您有一个链表a1-> a2 ....-> an-> b1-> b2 .... bn,并且您想将其重新排列为a1-> b1-> a2-> b2- > ..... an-> bn。您不知道链表的长度,但您所知道的只是它是偶数。
(这两个链表的长度相同)
您可以让一个指针p1(快速指针)每移动2个元素就会移动p2。当p1到达链接列表的末尾时,p2将位于端点处。然后,将p1返回到最前面,然后开始“编织”元素。在每次迭代中,p2选择一个元素并将其插入到p1之后。
我不明白当p1到达链接列表的末尾时,p2会处于中点。如果n = 3(长度= 6),这就是我的想象。下面的每个步骤代表一个迭代。
我尝试了由4个元素组成的链接列表,并成功实现了结果。但是,我无法解决一般情况,因为我的指针悬空了。我被困在python中是否可以为该问题提供代码。这是我的代码:
def runner_technique_ex(self, head):
"""
Assume the length of the ll that we will run thru will be even
:param head:
:return:
"""
slow = head
fast = head.next
while fast.next is not None:
slow = slow.next
fast = fast.next.next
fast = head
slow = slow.next
while slow.next is not None:
tempSlow = slow
tempFast = fast.next
fast.next = tempSlow
slow = slow.next
tempSlow.next = tempFast
tempFast.next = slow
答案 0 :(得分:0)
经过一番挣扎弄清楚了
def runner_technique_ex(self, head):
"""
Assume the length of the ll that we will run thru will be even
:param head:
:return:
"""
slow = head
fast = head.next
while fast.next is not None:
slow = slow.next
fast = fast.next.next
fast = head
slow = slow.next
newHead = Node(fast.data)
newHeadExtraPointer = newHead
newHead.next = Node(slow.data)
newHead = newHead.next
while slow.next is not None:
fast = fast.next
slow = slow.next
fastNextNode = Node(fast.data)
slowNextNode = Node(slow.data)
fastNextNode.next = slowNextNode
newHead.next = fastNextNode
newHead = fastNextNode.next
return newHeadExtraPointer