码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Reorder List [143]

时间:2014-06-30 10:11:14      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   面试   

【题目】

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);
    }
};


LeetCode: Reorder List [143],布布扣,bubuko.com

LeetCode: Reorder List [143]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/35780295

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!