Date and Time: Jul 31, 2024, 22:40 (EST)
Link: https://leetcode.com/problems/reorder-list/
You are given the head of a singly linked-list. The list can be represented as:
Reorder the list to be on the following form:
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
Example 1:
Input:
Output:
Explanation:
Example 2:
Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]
-
The number of nodes in the list is in the range
[1, 5 * 10^4]. -
1 <= Node.val <= 1000
-
Use fast-slow pointers method to find the middle node to split the linked-list into two lists.
-
Now we split the linked-list and reverse the right list. Remeber to set the middle node's next to
None. (This is the way how we split). -
Start changing linked-list from
leftandright, untilrightisNull. -
We check
while prev.nextinstead ofwhile prev, because weprevwill beNonein the end, and it will return an error thatCycle in the list.
# 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: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
fast, slow = head, head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
prev = None
while slow:
tmp = slow.next
slow.next = prev
prev = slow
slow = tmp
while prev.next:
tmp1, tmp2 = head.next, prev.next
head.next = prev
prev.next = tmp1
head, prev = tmp1, tmp2Time Complexity:
Space Complexity:
| Language | Runtime | Memory |
|---|---|---|
| Python3 | ms | MB |
| Java | ms | MB |
| C++ | ms | MB |

