题目地址(143. 重排链表)
https://leetcode-cn.com/problems/reorder-list/
题目描述
给定一个单链表 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
前置知识
公司
- 暂无
思路
关键点
代码
解法一
- 语言支持:Python3
Python3 Code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# 使用线性表
if not head:
return
vec = list()
node = head
while node:
vec.append(node)
node = node.next
i,j = 0,len(vec)-1
while i<j:
vec[i].next = vec[j]
i += 1
# 判断是否两个节点是否相遇
if i == j:
break
vec[j].next = vec[i]
j -= 1
# 重排 需要断开连接
vec[i].next = None
复杂度分析
令 n 为数组长度。
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)
解法二
- 语言支持:Python3
Python3 Code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# 寻找链表中点 + 反转右端链表 + 合并链表
def findCenter(head:ListNode)->ListNode:
slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
def reverse(head:ListNode)->ListNode:
pre = None
cur = head
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
return pre
def merge(head1:ListNode,head2:ListNode)->ListNode:
while head1 and head2:
l1 = head1.next
l2 = head2.next
head1.next = head2
head1 = l1
head2.next = head1
head2 = l2
pre = findCenter(head)
head2 = reverse(pre.next)
pre.next = None
merge(head,head2)
复杂度分析
令 n 为数组长度。
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)