[leetcode-143]Reorder List(c)

来源:互联网 发布:电视直播电脑版软件 编辑:程序博客网 时间:2024/05/16 01:52

问题描述:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}.

分析:这道题的主要是思路是将list切割为两半,然后第二部分进行反转,然后再拼接在一起。

代码如下:16ms

struct ListNode *reverse(struct ListNode* head) {    struct ListNode *prev = NULL;    struct ListNode *cur = head;    struct ListNode *next;    while (cur) {        next = cur->next;        cur->next = prev;        prev = cur;        cur = next;    }    return prev;}void reorderList(struct ListNode* head) {    if (!head)        return;    struct ListNode* cur = head;    struct ListNode* prev = NULL;    int length = 0;    while (cur) {        length++;        cur = cur->next;    }    int leftLen = (length - 1) / 2 + 1;    //find the next list    length = 0;    cur = head;    while (length<leftLen) {        prev = cur;        cur = cur->next;        length++;    }    if(prev)        prev->next = NULL;    struct ListNode *right = reverse(cur);//将cur后面的list反转    struct ListNode *left = head;    struct ListNode *tmp;    while (left && right) {        tmp = left->next;        left->next = right;        left = tmp;        tmp = right->next;        right->next = left;        right = tmp;    }}
0 0
原创粉丝点击