LeetCode 143.重排链表

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

/**
 * 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||!head->next||!head->next->next)return ;
        auto p=head,q=head;
        while(q->next&&q->next->next){
            p=p->next;
            q=q->next->next;
        }
        auto a=p,b=a->next;
        while(b){
            auto c=b->next;
            b->next=a;
            a=b;
            b=c;
        }
        p->next=NULL;
        while(head&&head!=a){
            b=a->next;
            a->next=head->next;
            head->next=a;
            head=head->next->next;
            a=b;
        }
    }
};

猜你喜欢

转载自www.cnblogs.com/programyang/p/11273496.html