标签:style blog http color os art
Not very hard to figure out the solution: splitting the list into 2 halves; reverse the 2nd half and interleave the two halves.
But it takes some time to code due to a lot of details - majority of them are boudary conditions.
class Solution { public: ListNode *findHalf(ListNode *p) { ListNode dummy(0); dummy.next = p; ListNode *sp = &dummy; ListNode *fp = &dummy; bool bOdd = false; ListNode *toCut = NULL; while(fp) { toCut = sp; sp = sp->next; fp = fp->next; if(fp) fp = fp->next; else bOdd = true; } if(bOdd) { toCut->next = NULL; return sp; } else { ListNode *tmp = sp->next; sp->next = NULL; return tmp; } } ListNode * interleave(ListNode *p0, ListNode *p1) { ListNode *pa = p0; ListNode *pb = pa->next; ListNode *pc = p1; ListNode *pd = pc->next; while(pa && pc) { pa->next = pc; pc->next = pb; pa = pb; if(pb) pb = pb->next; pc = pd; if(pd) pd = pd->next; } return p0; } ListNode *reverseList(ListNode *p) { if(!p->next) return p; ListNode *p0 = NULL; ListNode *p1 = p; ListNode *p2 = p->next; // Reverse while(p1) { p1->next = p0; p0 = p1; p1 = p2; if(p2) p2 = p2->next; } return p0; } void reorderList(ListNode *head) { if(!head || !head->next) return; ListNode *p1 = findHalf(head); p1 = reverseList(p1); interleave(head, p1); } };
LeetCode "Reorder List",布布扣,bubuko.com
标签:style blog http color os art
原文地址:http://www.cnblogs.com/tonix/p/3852552.html