赞
踩
L0 → L1 → … → Ln - 1 → Ln
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
快慢指针法
。交替合并
。/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ void reorderList(struct ListNode* head) { if (head == NULL || head->next == NULL || head->next->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 *secondHalf = slow->next; slow->next = NULL; // 反转后半部分链表 struct ListNode *prev = NULL; struct ListNode *curr = secondHalf; struct ListNode *nextNode; while (curr != NULL) { nextNode = curr->next; curr->next = prev; prev = curr; curr = nextNode; } secondHalf = prev; // 合并两个部分 struct ListNode *firstHalf = head; while (secondHalf != NULL) { struct ListNode *nextFirst = firstHalf->next; struct ListNode *nextSecond = secondHalf->next; firstHalf->next = secondHalf; secondHalf->next = nextFirst; firstHalf = nextFirst; secondHalf = nextSecond; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。