LeetCode143 Reorder List

题目链接:

https://leetcode.com/problems/reorder-list/

题目大意:

将一个链表L0→L1→…→Ln-1→Ln,重新排列成L0→Ln→L1→Ln-1→L2→Ln-2→…。

不能通过改变节点的数据来实现,只能通过改变节点的指向来实现。

分析:

没什么好说的,善用指针的引用。目前自己关于链表存在的最大的问题就是,搞不清楚指向,对指针及指针的引用还是懵懵懂懂的样子。题挺简单的,把链表从中间分成两部分,将后一般递归到底,在递归返回的时候,将节点不断插入前一部分的链表中去。LeetCode上关于链表的题,确实让我进一步理解了指针。加油↖(^ω^)↗

代码:

class Solution {
public:
void ReorderList(ListNode* &pre,ListNode* newList){
    if (newList == NULL)
    {
        return;
    }
    ReorderList(pre,newList->next);
    ListNode* tmp = pre->next;
    pre->next = newList;
    newList->next = tmp;
    pre = tmp;

}

void partitionList(ListNode* &list){
    ListNode* low = list;
    ListNode* high = list;
    ListNode* pre = NULL;
    ListNode* newList = NULL;
    while (high->next != NULL && high->next->next != NULL)
    {
        pre = low;
        low = low->next;
        high = high->next->next;
    }
    newList = low->next;
    low->next = NULL;
    ListNode* ptr = list;
    ReorderList(ptr,newList);
}
    void reorderList(ListNode* head) {
        if(head==NULL){
            return;
        }
        partitionList(head);
    }
};

你可能感兴趣的:(LeetCode,链表,143)