题目:
重排链表:给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→… 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
思路:
使用了懒人做法,使用了栈,应该还有更好的方法,想到后做补充。
程序:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return None
myStack = []
index1 = head
counter = 0
while index1:
myStack.append(index1)
index1 = index1.next
counter += 1
num_rotate = counter // 2
index2 = head
while num_rotate:
tmp_node = myStack.pop()
tmp_node.next = index2.next
index2.next = tmp_node
index2 = tmp_node.next
num_rotate -= 1
index2.next = None