# 重排链表
给定一个单链表 L
的头节点 head
,单链表 L
表示为:
L0 → L1 → … → Ln-1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入: head = [1,2,3,4]
输出: [1,4,2,3]
示例 2:
输入: head = [1,2,3,4,5]
输出: [1,5,2,4,3]
提示:
- 链表的长度范围为
[1, 5 * 104]
1 <= node.val <= 1000
## template
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
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 = head
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
```
## 答案
```python
```
## 选项
### A
```python
```
### B
```python
```
### C
```python
```