Leetcode Reorder List

来源:互联网 发布:windows cmd shell 编辑:程序博客网 时间:2024/05/29 16:59

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



先通过快慢指针找到转换节点,将转换节点后半部分逆序,然后再将转换节点依次插入前半部分即可。

代码如下:

/** * 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 || !head->next)                return;                ListNode* p1,*p2;        p1 = p2 = head;        while(p2->next && p2->next->next)        {            p1 = p1->next;            p2 = p2->next->next;        }                ListNode* cur = p1->next;        ListNode* next;        while(cur->next)        {            next = cur->next;            cur->next=next->next;            next->next = p1->next;            p1->next = next;        }                p2 = head;        cur = p1->next;        while(p2!=p1)        {            p1->next = cur->next;            cur->next = p2->next;            p2->next = cur;            p2 = cur->next;            cur = p1->next;        }    }};



原创粉丝点击