【LeetCode 143】Reorder List

题目描述

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

思路

先用快慢指针的方法找到中间节点;
把后半部分反转;
合并两部分。

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    void reorderList(ListNode* head) {
        if (head == NULL || head->next == NULL) return;
        
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast->next != NULL && fast->next->next != NULL) {
            fast = fast->next->next;
            slow = slow->next;
        }
        
        ListNode* mid = slow->next;
        slow->next = NULL;
        
        ListNode* pre = NULL;
        while (mid != NULL) {
            ListNode* tmp = mid->next;
            mid->next = pre;
            pre = mid;
            mid = tmp;
        }
        
        ListNode* left = head;
        ListNode* right = pre;
        
        while (left && right) {
            ListNode* nxt1 = left->next;
            ListNode* nxt2 = right->next;
            left->next = right;
            right->next = nxt1;
            left = nxt1;
            right = nxt2;
        }
    }
};
发布了340 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/105539803
今日推荐