solution.md 2.0 KB
Newer Older
ToTensor's avatar
ToTensor 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
# 重排链表

<p>给定一个单链表 <code>L</code><em> </em>的头节点 <code>head</code> ,单链表 <code>L</code> 表示为:</p>

<p><code> L<sub></sub>→ L<sub></sub>→ … → L<sub>n-1 </sub>→ L<sub></sub></code><br />
请将其重新排列后变为:</p>

<p><code>L<sub></sub>→ L<sub></sub>→ L<sub></sub>→ L<sub>n-1 </sub>→ L<sub></sub>→ L<sub>n-2 </sub>→ …</code></p>

<p>不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。</p>

<p> </p>

<p><strong>示例 1:</strong></p>

<p><img alt="" src="https://pic.leetcode-cn.com/1626420311-PkUiGI-image.png" style="width: 240px; " /></p>

<pre>
<strong>输入: </strong>head = [1,2,3,4]
<strong>输出: </strong>[1,4,2,3]</pre>

<p><strong>示例 2:</strong></p>

<p><img alt="" src="https://pic.leetcode-cn.com/1626420320-YUiulT-image.png" style="width: 320px; " /></p>

<pre>
<strong>输入: </strong>head = [1,2,3,4,5]
<strong>输出: </strong>[1,5,2,4,3]</pre>

<p> </p>

<p><strong>提示:</strong></p>

<ul>
	<li>链表的长度范围为 <code>[1, 5 * 10<sup>4</sup>]</code></li>
	<li><code>1 <= node.val <= 1000</code></li>
</ul>


## 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

```