文章目录
- AcWing 3757. 重排链表
- AC代码
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; } }
/** * 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; }