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上也有了,这题的做法有很多,我是用的是一个舍友给我提供的一种方法,先把后面部分反转在重新插入即可。
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int length; length = 0; ListNode *p,*q,*t; p = head; while(p) { p = p->next; length++; } if(length<=2) return ; p = head; length = length/2; for(int i = 0;i<length;i++) { p = p->next; } t = p->next; p->next = NULL; p = t; t = t->next; p->next = NULL; while(t) { q = t->next; t->next = p; p = t; t = q; } t = head; while(p&&t) { q = p->next; p->next = t->next; t->next = p; t = t->next->next; p = q; } } };