重新排列链表 考研题C语言
时间: 2023-10-19 07:09:24 浏览: 98
题目描述:
给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln-1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入: head = [1,2,3,4]
输出: [1,4,2,3]
示例 2:
输入: head = [1,2,3,4,5]
输出: [1,5,2,4,3]
提示:
链表的长度范围为 [1, 5 * 10^4]
1 <= node.val <= 1000
思路:
1. 找到链表中点
2. 将链表分为两个部分
3. 反转第二个链表
4. 合并两个链表
C语言代码实现:
```
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
void mergeList(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* l1_tmp;
struct ListNode* l2_tmp;
while (l1 != NULL && l2 != NULL) {
l1_tmp = l1->next;
l2_tmp = l2->next;
l1->next = l2;
l1 = l1_tmp;
l2->next = l1;
l2 = l2_tmp;
}
}
void reorderList(struct ListNode* head){
if (head == NULL || head->next == NULL) {
return;
}
struct ListNode* slow = head;
struct ListNode* fast = head;
while (fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
struct ListNode* l1 = head;
struct ListNode* l2 = slow->next;
slow->next = NULL;
l2 = reverseList(l2);
mergeList(l1, l2);
}
```
阅读全文