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: ListNode* reserve(ListNode *head){ if(head==NULL || head->next==NULL)return head; ListNode* prev=NULL; ListNode* cur=head; ListNode* next=NULL; while(cur){ next=cur->next; cur->next=prev; prev=cur; cur=next; } return prev; } ListNode* findMid(ListNode *head){ if(head==NULL || head->next==NULL)return head; ListNode*prev=NULL; ListNode*p1=head; ListNode*p2=head; while(p2){ prev=p1; p1=p1->next; p2=p2->next; if(p2)p2=p2->next; } prev->next=NULL; return p1; } ListNode* merge(ListNode*head1, ListNode*head2){ ListNode*p1=head1; ListNode*p2=head2; ListNode*head=NULL, *p=NULL; while(p2){ if(head==NULL)head=p1; else p->next=p1; p=p1; p1=p1->next; p->next=p2; p=p2; p2=p2->next; } p->next=p1; return head; } void reorderList(ListNode *head) { if(head==NULL || head->next==NULL)return; ListNode* head2 = findMid(head); head2 = reserve(head2); head=merge(head, head2); } };
LeetCode: Reorder List [143],布布扣,bubuko.com
原文地址:http://blog.csdn.net/harryhuang1990/article/details/35780295