Reorder List

来源:互联网 发布:快速弄到钱网络偏门2万 编辑:程序博客网 时间:2024/06/07 02:34

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

Subscribe to see which companies asked this question.

解题技巧:

先将链表分成两部分,然后翻转链表后半部分,最后将两部分链表进行组合

代码:

#include <iostream>using namespace std;struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};void reorderList(ListNode* head){    ListNode *p, *q, *h2, *tmp;    //求链表的长度    int len = 0, ll;    p = head;    while(p)    {        len ++;        p = p->next;    }    if(len == 0 || len == 1) return;    //将链表分成两半    p = head;    ll = len%2 ? len/2+1: len/2;    for(int i = 1; i < ll; i ++)    {        p = p->next;    }    h2 = p->next;    p->next = NULL;    //将后半部分链表翻转    p = h2;    q = h2->next;    h2->next = NULL;    while(q != NULL)    {        tmp = q->next;        q->next = p;        p = q;        q = tmp;    }    h2 = p;    //合并    p = head, q = h2;    ListNode *pn, *qn;    while(q)    {        pn = p->next;        qn = q->next;        p->next = q;        q->next = pn;        p = pn;        q = qn;    }}int main(){    ListNode *head = NULL, *p;    int x;    while(cin >> x)    {        ListNode *tmp = new ListNode(x);        if(head != NULL) tmp->next = head;        head = tmp;    }    p = head;    while(p)    {        cout<<p->val<<" ";        p = p->next;    }    cout<<endl;    reorderList(head);    p = head;    while(p)    {        cout<<p->val<<" ";        p = p->next;    }    cout<<endl;}



0 0
原创粉丝点击