NC2 重排链表
条件:
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→
你不能只是单纯改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
使用栈,依次从"头-尾-头-尾"出栈
eg:1》2》3》4》5
第一次出栈:1》5
第二次出栈:1》5》2
第三次出栈:1》5》2》4
第四次出栈:1》5》2》4》3
"""
代码python实现:
"""
class Solution:
def reorderList(self , head ):
# write code here
if not head:
return
stack = [2,3,4,5]
s = head
#将首节点之外的其它节点压入栈
while s.next:
stack.append(s.next)
s = s.next
# 重新定义 s
s = head
# n 用来限制出栈方式和顺序
n = 0
while stack:
if n % 2 == 0:
one = stack.pop() # 当括号内为空时则删除该列表最后一个元素并将其返回.
else:
one = stack.pop(0)
one.next = None
s.next = one
s = s.next
n += 1