[LeetCode]143 重排链表

题目描述

给定一个单链表 LL0→L1→…→Ln-1→Ln ,将其重新排列后变为:L0→LnL1→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.

思路

  • 找到链表尾端,交换

代码

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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if head == None or head.next == None:
return

front = head
rear = head.next
while rear != None and rear.next != None:
front = front.next
rear = rear.next.next

p = front.next
front.next = None

cur = None
while p != None:
q = p.next
p.next = cur
cur = p
p = q

front = head
while front != None and cur != None:
tmp = cur.next
cur.next = front.next
front.next = cur
front = front.next.next
cur = tmp