Leetcode- 143. Reorder List

来源:互联网 发布:好看的皮鞋淘宝店铺 编辑:程序博客网 时间:2024/06/03 12:28


解题思路:使用快慢指针找到链表的中间位置(代码需要写的非常小心)。对于后半部分的链表逆序(如果不使用哑节点dummy方法,需要在之前判断链表元素个数小于1时直接返回。)


/** * 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 || head->next==NULL)            return;        ListNode *slow=head,*fast=head->next;        while(fast && fast->next){            fast = fast->next->next;            slow = slow->next;        }                ListNode *newh = slow->next;        slow->next = NULL;                fast = newh->next;        newh->next =NULL;                while(fast){            ListNode *tmp  = fast->next;            fast->next = newh;            newh = fast;            fast = tmp;        }                ListNode *cur = head;        while(cur && newh){            ListNode *post = cur->next;            ListNode *tmp = newh;            newh = newh->next;            cur->next = tmp;            tmp->next = post;            cur = post;        }    }};


0 0