1. 题目描述
143.重排链表
给定一个单链表 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.
2. 代码实现
使用栈,然后依次从头尾头尾出栈:
例如对于:1->2->3->4->5
第一次出栈:1->5
第二次出栈:1->5->2
第三次出栈:1->5->2->4
第四次出栈:1->5->2->4->3
执行用时 :136 ms, 在所有 Python 提交中击败了8.77%的用户
内存消耗 :30.7 MB, 在所有 Python 提交中击败了50.00%的用户
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if not head: return
stack = []
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