LeetCode Reorder List

本文介绍了一种链表重排序算法的实现方法,通过将链表后半部分反转再与前半部分交错合并来达到重排序的目的。文章详细阐述了算法步骤,并提供了两种不同版本的代码实现。

智商拙计,做了有些时间才对,抱着试一试的心态先用了个递归的暴力找最后节点的方法,超时,关键是解决如何高效的取得最后一个节点,可以先把后半截链表倒转一下,然后merge两个链表,总共节点数为偶数时merge时刚刚能够一一配对,奇数时则会多出一个,补上即可。中间分割链表的时候不小心又出了好些bug,有些事情总是要被拆穿啊~

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode* head) {
        if (head == NULL) {
            return NULL;
        }
        ListNode* pre = NULL;
        ListNode* cur = head;
        while (cur != NULL) {
            ListNode* tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }

    void reorderList(ListNode *head) {
        if (head == NULL || head->next == NULL) {
            return;
        }
        int num = 0;
        ListNode* cur = head;
        while (cur != NULL) {
            num++;
            cur = cur->next;
        }
        // seperate list, find middle node as the head of the new list
        int ridx = num / 2;
        ListNode* rhead = NULL;
        cur = head;
        for (int i=0; true; i++) {
            if (i == ridx - 1) {
                rhead = cur->next;
                cur->next = NULL;
                break;
            }
            cur = cur->next;
        }
 
        rhead = reverse(rhead);
        // build final list
        cur = head;
        head = head->next;
    
        cur->next = rhead;
        cur = rhead;
        rhead = rhead->next;
            
        while (head != NULL && rhead != NULL) {
            cur->next = head;
            cur = head;
            head = head->next;
                
            cur->next = rhead;
            cur = rhead;
            rhead = rhead->next;
        }
        cur->next = rhead; // there must be only one node left(odd case) or NULL(even case)
    }
};

还是附上naive版本吧,too young, too simple

/**
 * 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* tail = head;
        ListNode* prev = NULL;
        while (tail->next != NULL) {
            prev = tail;
            tail = tail->next;
        }
        prev->next = NULL;
        reorderList(head->next);
        tail->next = head->next;
        head->next = tail;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值