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}
.
基本思路:
先找到中间结点。
然后将后半部分链表进行反转;
再合并这两个链表。
在leetcode上实际运行时间为72ms。
/** * 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 *walker = head; ListNode *runner = head->next; while (runner && runner->next) { walker = walker->next; runner = runner->next; runner = runner->next; } ListNode middle(0); runner = walker; walker = walker->next; runner->next = NULL; while (walker) { ListNode *bak = walker->next; walker->next = middle.next; middle.next = walker; walker = bak; } while (middle.next) { ListNode *bak = middle.next->next; middle.next->next = head->next; head->next = middle.next; head = head->next->next; middle.next = bak; } } };
版权声明:本文博主原创文章,博客,未经同意不得转载。