Reorder List

问题:Given a singly linked list LL0L1→…→Ln-1Lnreorder it to: L0LnL1Ln-1L2Ln-2→…

思路:采用的原来的简单做法,找到中间位置、断开、后半段逆转、再合并。http://blog.csdn.net/ojshilu/article/details/12222035

代码:

/**
 * 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 == NULL)
        return;
    //寻找中间结点位置  
    ListNode *fast=head, *slow=head;  
    while(fast->next!=NULL && fast->next->next!=NULL)  
    {  
        fast = fast->next->next;  
        slow = slow->next;  
    }  
    ListNode *mid = slow->next;  
    slow->next = NULL; //正式将原链表一切为二  
  
    //将后半部分链表反转  
    ListNode *s2 = NULL;  
    ListNode *tmp;  
    while(mid!=NULL)  
    {  
        tmp = mid->next;  
        mid->next = s2;  
        s2 = mid;  
        mid = tmp;  
    }
      
    //交叉合并两个链表  
    ListNode *s1 = head;  
    while(s2!=NULL)  
    {  
        tmp = s2->next;  
        s2->next = s1->next;  
        s1->next = s2;     
        s1 = s1->next->next;  
        s2 = tmp;  
    }  
    
    }
};

你可能感兴趣的:(Reorder List)