Reorder List

来源:互联网 发布:神鬼传奇怪物数据 编辑:程序博客网 时间:2024/05/29 18:54

Given a singly linked list L: 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}.


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    void reorderList(ListNode *head) {        if (head == NULL)        {            return;        }                ListNode *p = head;        int len = 0;        while (p)        {            len++;            p = p->next;        }        int steps = (len-1)/2;        p = head;        while (steps)        {            p = p->next;            steps--;        }        ListNode *q = p->next;        p->next = NULL;        ListNode *prev = NULL;        while (q)        {            ListNode *r = q->next;            q->next = prev;            prev = q;            q = r;        }        p = head;        q = prev;        while (q)        {            ListNode *firstTemp = p->next;            ListNode *secondTemp = q->next;            p->next = q;            q->next = firstTemp;            p = firstTemp;            q = secondTemp;        }    }};


0 0
原创粉丝点击