LeetCoder 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}.

思路:

1把整个链表划分成2个等长的子链表,如果原链表长度为奇数,那么第一个子链表的长度多1。

2.翻转第二个子链表;

3.将两个子链表合并。

代码:

class Solution {
public:
    void reorderList(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return ;
        ListNode* slow_ptr = head;
        ListNode* fast_ptr = head;
        //找到中间节点位置
        while(fast_ptr->next != NULL)
        {
            fast_ptr = fast_ptr->next;
            if(fast_ptr->next !=NULL)
                fast_ptr = fast_ptr->next;
            else
                break;
            slow_ptr = slow_ptr->next;
        }
        //设置两个新链表的头结点
        ListNode* head1 = head, *head2 = slow_ptr->next;
        slow_ptr->next = NULL;
        ListNode* cur = head2, *post = cur->next;
        head2->next = NULL;
        while(post != NULL)//翻转第二个链表
        {
            ListNode* tmp = post->next;
            post->next = cur;
            cur = post;
            post = tmp;
        }
        head2 = cur;
        ListNode* p = head1;
        ListNode* q = head2;
        while(q != NULL)//将两个链表合并即得到结果
        {
            ListNode* tmp1 = p->next;
            ListNode* tmp2 = q->next;
            p->next = q;
            q->next = tmp1;
            p = tmp1;
            q = tmp2;
        }
    }
};



你可能感兴趣的:(LeetCode,链表,面试,合并)