Leetcode: Reorder List

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,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) {
            return;
        }
        
        // Find the middle
        ListNode *fast = head;
        ListNode *slow = head;
        while (fast != NULL && fast->next != NULL) {
            fast = fast->next->next;
            slow = slow->next;
        }
        
        // Reserve the second half
        ListNode *head2 = NULL;
        ListNode *tmp = NULL;
        while (slow != NULL) {
            tmp = slow->next;
            slow->next = head2;
            head2 = slow;
            slow = tmp;
        }
        
        ListNode *head1 = head;
        while (head1 != NULL && head2 != NULL && head1 != head2) {
            tmp = head1->next;
            head1->next = head2;
            head1 = tmp;
            tmp = head2->next;
            if (tmp != NULL) {
                head2->next = head1;
            }
            head2 = tmp;
        }
    }
};

======================第二次==============================

两个链表合并的时候,需要注意第二个链表的NULL判断,否则会形成循环链表。

/**
 * 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) {
        ListNode *fast = head;
        ListNode *tail = head;
        while (fast != NULL && fast->next != NULL) {
            fast = fast->next->next;
            tail = tail->next;
        }
        
        ListNode *tmp = NULL;
        ListNode *prev = NULL;
        while (tail != NULL) {
            tmp = tail->next;
            tail->next = prev;
            prev = tail;
            tail = tmp;
        }
        
        ListNode *head1 = head;
        ListNode *head2 = prev;
        while (head1 != NULL && head2 != NULL) {
            tmp = head1->next;
            head1->next = head2;
            head1 = tmp;
            tmp = head2->next;
            if (tmp != NULL) {
                head2->next = head1;    
            }
            head2 = tmp;
        }
    }
};


你可能感兴趣的:(LeetCode)