143. Reorder List

本文介绍了一种链表的重构算法,该算法将一个链表分为两部分并反转第二部分,然后交错合并这两部分。通过这种方式可以有效地改变链表的顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Solution {
public:
void reorderList(ListNode* head) {
ListNode *head1 = head, *head2 = NULL;
int len = 0, count = 1;
while(head) { //遍历链表
head = head -> next;
++len;
}
head = head1;
if(len <= 2 || !head)
return;
while(count != ceil(len / 2.0)) { /*把链表切成两段h1 h2 */
head = head -> next;
++count;
}
head2 = head -> next;
head -> next = NULL;
head = head1;
head2 = reverse(head2);//reverse head2
for(ListNode *i = head1, *j = head2; i&&j; head1 = i, head2 = j) {//i和j存之后的两个链表节点  最初判断条件只有i 不是i&&j 这样导致后面调用head2 -》next时候head2可能为null越界

if(head1 -> next)
i = head1 -> next;
else
i = NULL;
head1 -> next = head2;
if(head2 -> next)
j = head2 -> next;
else
j = NULL;
head2 -> next = i;
}
return;
}
ListNode *reverse(ListNode * head) {
ListNode *t, *y = head, *r = NULL;
if(head -> next == NULL)
return head;
while(y != NULL) {
t = y -> next;
y -> next = r;
r = y;
y = t;
}
return r;
}
};

转载于:https://www.cnblogs.com/bloomingFlower/p/7739578.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值