`
SunnyYoona
  • 浏览: 367233 次
社区版块
存档分类
最新评论

LeetCode之Reorder List

 
阅读更多

【题目】

Given a singly linked listL:L0L1→…→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→...

【分析】

题目规定要 in-place,也就是说只能使用 O(1) 的空间。
可以找到中间节点,断开,把后半截单链表 reverse 一下,再合并两个单链表。

【代码】

/*********************************
*   日期:2014-01-31
*   作者:SJF0115
*   题号: Reorder List 
*   来源:http://oj.leetcode.com/problems/reorder-list/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* reorderList(ListNode *head) {
        if(head == NULL || head->next == NULL){
            return head;
        }
        //找中间节点
        ListNode *slow = head,*fast = head,*pre = NULL,*pre2 = NULL,*temp = NULL;
        while(fast != NULL && fast->next != NULL){
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        //在中间截断成两个单链表
        pre->next = NULL;
        ListNode *head2 = reverse(slow);
        //合并
        pre = head;
        pre2 = head2;
        while(pre->next != NULL){
            temp = pre2->next;
            //合并
            pre2->next = pre->next;
            pre->next = pre2;
            //下一个元素
            pre = pre->next->next;
            pre2 = temp;
        }
        pre->next = pre2;
        return head;
    }
private:
    ListNode* reverse(ListNode *head){
        if(head == NULL || head->next == NULL){
            return head;
        }

        ListNode *dummy = (ListNode*)malloc(sizeof(ListNode));
        dummy->next = head;

        ListNode *tail = head,*cur = head->next;
        while(cur != NULL){
            //删除cur元素
            tail->next = cur->next;
            //插入
            cur->next = dummy->next;
            dummy->next = cur;
            cur = tail->next;
        }
        return dummy->next;
    }
};

int main() {
    Solution solution;
    int A[] = {1,2,3,4,5,6};
    ListNode *head = (ListNode*)malloc(sizeof(ListNode));
    head->next = NULL;
    ListNode *node;
    ListNode *pre = head;
    for(int i = 0;i < 6;i++){
        node = (ListNode*)malloc(sizeof(ListNode));
        node->val = A[i];
        node->next = NULL;
        pre->next = node;
        pre = node;
    }
    head = solution.reorderList(head->next);
    while(head != NULL){
        printf("%d ",head->val);
        head = head->next;
    }
    //printf("Result:%d\n",result);
    return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics