Skip to content

[LeetCode] 143. Reorder List #93

Open
@frdmu

Description

@frdmu

You are given the head of a singly linked-list. The list can be represented as:

L0 → L1 → … → Ln - 1 → Ln

Reorder the list to be on the following form:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

You may not modify the values in the list's nodes. Only nodes themselves may be changed.

 

Example 1:
reorder1linked-list

Input: head = [1,2,3,4]
Output: [1,4,2,3]

Example 2:
reorder2-linked-list

Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]

Constraints:

  • The number of nodes in the list is in the range [1, 5 * 104].
  • 1 <= Node.val <= 1000

解法:
分三步:

  • 快慢指针找中点
  • 翻转链表
  • 连接两个链表

代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if (!head || !head->next || !head->next->next) return;

        ListNode *slow = head, *fast = head;
        while(fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;    
        }
        ListNode *mid = slow->next;
        slow->next = NULL;
         
        ListNode *cur = mid, *pre = NULL;
        while (cur) {
            ListNode *next = cur->next;  
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        
        ListNode *p = head;
        while (pre) {
            ListNode *q = pre;
            pre = pre->next;
            q->next = p->next;         
            p->next = q;
            p = p->next->next;
        }
    }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions