39:Reorder List

本文介绍了一种链表重组算法,该算法将链表分为两部分并逆序后半部分,再交替合并为新链表。提供了完整的C++实现代码。

题目:Given a singly linked list L : L0>L1>...>Ln1>Ln, reorder it to: L0>Ln>L1>Ln1>L2>Ln2>
You must do this in-place without altering the nodes’ values.
For example, Given {1,2,3,4}, reorder it to {1,4,2,3}.

解析:将链表从中间断开,然后将后半段链表逆序,最后将前半段链表以及逆过序后的后半段链表合并在一起

解题代码如下:

class Solution {
public:
        void reorderList(ListNode *head) {
                if (!head || !head -> next) return;
                //计算链表总长度
                int len = 0;
                ListNode *cur = head;
                while (cur != nullptr) {
                        ++len;
                        cur = cur -> next;
                }

                int mid = len % 2 != 0 ? len / 2 + 1 : len / 2;
                ListNode* mid_ptr = head;
                for (int i = 0; i != mid - 1; ++i)
                        mid_ptr = mid_ptr -> next;

                // 从中间将原先链表分成两个链表
                ListNode* head2 = mid_ptr -> next;
                mid_ptr -> next = nullptr;
                // 将后半段链表逆序
                head2 = reverseList(head2);

                //将这两个链表再次合并成一个链表
                ListNode *cur1 = head, *cur2 = head2;
                while (cur2 != nullptr) {
                        ListNode* tmp = cur2 -> next;
                        cur2 -> next = cur1 -> next;
                        cur1 -> next = cur2;
                        cur1  = cur1 -> next -> next;
                        cur2 = tmp;
                }
        }
private:
        ListNode* reverseList(ListNode* head) {
                if (!head) return head;
                ListNode dummy{-1};
                dummy.next = head;

                ListNode* cur = head;
                while (cur -> next != nullptr) {
                        ListNode* tmp = cur -> next;
                        cur -> next = tmp -> next;
                        tmp -> next = dummy.next;
                        dummy.next = tmp;
                }
                return head;
        }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值