题目
给定一个单链表 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 * 104]
1 <= node.val <= 1000
解题
方法一:找链表中点 原地反转链表 合并链表
思路
找到链表中点后把链表分成两部分,对后面一部分链表进行原地反转,然后合并前后两部分链表。
代码
class Solution {
public void reorderList(ListNode head) {
if (head.next == null) {
return;
}
ListNode mid = getMid(head);
ListNode list1 = head, list2 = reverseLinkedList(mid.next);
mid.next = null;
mergeLinkedList(list1, list2);
}
public ListNode getMid(ListNode head) {
ListNode slow = head, fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode reverseLinkedList(ListNode head) {
ListNode curr = head, newNext = null, newPrev;
while(curr != null) {
newPrev = curr.next;
curr.next = newNext;
newNext = curr;
curr = newPrev;
}
return newNext;
}
public void mergeLinkedList(ListNode linkedList1, ListNode linkedList2) {
ListNode node1, node2;
while(linkedList1 != null && linkedList2 != null) {
node1 = linkedList1.next;
node2 = linkedList2.next;
linkedList1.next = linkedList2;
linkedList1 = node1;
linkedList2.next = linkedList1;
linkedList2 = node2;
}
}
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
ListNode* reverseList(ListNode* head) {
ListNode* curr = head, * newNext = nullptr, * newPrev;
while (curr) {
newPrev = curr->next;
curr->next = newNext;
newNext = curr;
curr = newPrev;
}
return newNext;
}
void mergeList(ListNode* list1, ListNode* list2) {
ListNode* next1, * next2;
while (list1 && list2) {
next1 = list1->next;
next2 = list2->next;
list1->next = list2;
list1 = next1;
list2->next = list1;
list2 = next2;
}
}
public:
void reorderList(ListNode* head) {
if (!head->next) return;
ListNode* slow = head, * quick = head;
while (quick && quick->next) {
slow = slow->next;
quick = quick->next->next;
}
ListNode* sec_half = reverseList(slow->next);
slow->next = nullptr;
mergeList(head, sec_half);
}
};
评论区