408数据结构真题2019-41
【摘要】
文章目录
AcWing 3757. 重排链表AC代码
AcWing 3757. 重排链表
本题链接:AcWing 3757. 重排链表
注:链接题目仅代表和本题大体相似 因为是考研笔...
AcWing 3757. 重排链表
本题链接:AcWing 3757. 重排链表
注:链接题目仅代表和本题大体相似
因为是考研笔试,本题代码以C语言去写


AC代码
代码解释:首先把链表对半分开,然后翻转后半段的链表,然后按照顺序依次加入到前半段链表中即可
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void rearrangedList(struct ListNode* head) {
if (!head->next) return;
int n = 0;
for (struct ListNode *p = head; p; p = p->next) n ++ ;
int left = (n + 1) / 2; // 前半段的节点数
//这一步操作保证我们分开的两个链表前半段元素必然大于等于后半段元素
//注意这里不是必须这么去这么划分,也可以为 n / 2,但是后续处理起来比较麻烦
//读者不妨自己动手去实现一下如果 n / 2 去划分的话,应该怎么写,代码同样放到后面,供读者参考
struct ListNode *a = head;
for (int i = 0; i < left - 1; i ++ ) a = a->next;
struct ListNode *b = a->next, *c = b->next;
a->next = b->next = NULL;
while (c) {
struct ListNode *p = c->next;
c->next = b;
b = c, c = p;
}
for (struct ListNode *p = head, *q = b; q;) {
struct ListNode *o = q->next;
q->next = p->next;
p->next = q;
p = p->next->next;
q = o;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void rearrangedList(struct ListNode* head) {
if (!head->next) return;
int n = 0;
struct ListNode *p, *q;
for (p = head; p; p = p->next) n ++ ;
int left = n / 2; // 前半段的节点数
struct ListNode *a = head;
for (int i = 0; i < left - 1; i ++ ) a = a->next;
struct ListNode *b = a->next, *c = b->next;
a->next = b->next = NULL;
while (c) {
struct ListNode *p = c->next;
c->next = b;
b = c, c = p;
}
struct ListNode *r;
for (p = head, q = b; p;) {
struct ListNode *o = q->next;
q->next = p->next;
p->next = q;
if (!p->next->next) r = p -> next;
p = p->next->next;
q = o;
}
if (q) r -> next = q;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
文章来源: chen-ac.blog.csdn.net,作者:辰chen,版权归原作者所有,如需转载,请联系作者。
原文链接:chen-ac.blog.csdn.net/article/details/121237559
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)