LeetCode: Reorder List [143]

【题目】

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


【题意】

    给定一个链表L: L0→L1→…→Ln-1→Ln,对他重新排序成L0→Ln→L1→Ln-1→L2→Ln-2→…


【思路】

        将链表对半截断,将后半部分链表倒置,然后把前后两个链表错位合并
        本题涉及三个典型的链表操作:
        1. 找链表中点
        2. 链表倒置
        3. 链表归并


【代码】

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reserve(ListNode *head){
        if(head==NULL || head->next==NULL)return head;
        ListNode* prev=NULL;
        ListNode* cur=head;
        ListNode* next=NULL;
        while(cur){
            next=cur->next;
            cur->next=prev;
            prev=cur;
            cur=next;
        }
        return prev;
    }
    ListNode* findMid(ListNode *head){
        if(head==NULL || head->next==NULL)return head;
        ListNode*prev=NULL;
        ListNode*p1=head;
        ListNode*p2=head;
        while(p2){
            prev=p1;
            p1=p1->next;
            p2=p2->next;
            if(p2)p2=p2->next;
        }
        prev->next=NULL;
        return p1;
    }
    ListNode* merge(ListNode*head1, ListNode*head2){
        ListNode*p1=head1;
        ListNode*p2=head2;
        ListNode*head=NULL, *p=NULL;
        while(p2){
            if(head==NULL)head=p1; 
            else p->next=p1;
            p=p1;
            p1=p1->next;
            p->next=p2;
            p=p2;
            p2=p2->next;
        }
        p->next=p1;
        return head;
    }
    void reorderList(ListNode *head) {
        if(head==NULL || head->next==NULL)return;
        ListNode* head2 = findMid(head);
        head2 = reserve(head2);
        head=merge(head, head2);
    }
};


猜你喜欢

转载自blog.csdn.net/HarryHuang1990/article/details/35780295
今日推荐