地址:http://oj.leetcode.com/problems/reorder-list/
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* reverseList(ListNode* head)
{
ListNode*pre=NULL, *cur=head, *next=NULL;
while(cur)
{
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
void reorderList(ListNode *head) {
if(head)
{
ListNode *p1 = head, *p2 = head, *nxt1 = NULL, *nxt2 = NULL;
while(p2 && p2->next)
{
p1 = p1->next;
p2 = p2->next;
if(p2)
p2 = p2->next;
}
p2 = p1->next;
p1->next = NULL;
p1 = head;
p2 = reverseList(p2);
//merge
while(p1 && p2)
{
nxt1 = p1->next;
nxt2 = p2->next;
p1->next = p2;
p2->next = nxt1;
p1 = nxt1;
p2 = nxt2;
}
}
}
};
//SECOND TRIALclass Solution {private :ListNode * reverseList ( ListNode * head ){if ( ! head || ! head -> next )return head ;ListNode * p = head , * pre = NULL , * nxt = NULL ;while ( p ){nxt = p -> next ;p -> next = pre ;pre = p ;p = nxt ;}return pre ;}public :void reorderList ( ListNode * head ) {if ( ! head || ! head -> next )return ;ListNode * p1 = head , * p2 = head , * pre = NULL , * nxt1 = NULL , * nxt2 = NULL ;while ( p1 ){p1 = p1 -> next ;pre = p2 ;if ( p1 ){p1 = p1 -> next ;p2 = p2 -> next ;}}p2 = pre -> next ;pre -> next = NULL ;p2 = reverseList ( p2 );p1 = head ;while ( p1 && p2 ){nxt1 = p1 -> next ;nxt2 = p2 -> next ;p1 -> next = p2 ;p1 = p2 -> next = nxt1 ;p2 = nxt2 ;}}};