思路
- 首先找到链表的中点(LeetCode #876)
// 找到中间节点
public ListNode getMid(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
- 将链表中点后面的元素反转(LeetCode #206)
// 对中间节点后面的部分进行反转
public ListNode reserve(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
- 中点前和中点后两个部分进行合并
// 合并两个链表
public void mager(ListNode head1, ListNode head2) {
while (head1 != null && head2 != null) {
ListNode next1 = head1.next;
ListNode next2 = head2.next;
head1.next = head2;
head2.next = next1;
head1 = next1;
head2 = next2;
}
}
代码实现(java)
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null) return;
// 首先获取链表的中点
ListNode mid = getMid(head);
// 然后对中点后面的部分进行反转
ListNode head2 = mid.next;
mid.next = null;
head2 = reserve(head2);
// 合并链表
ListNode head1 = head;
mager(head1, head2);
}
// 找到中间节点
public ListNode getMid(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
// 对中间节点后面的部分进行反转
public ListNode reserve(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
// 合并两个链表
public void mager(ListNode head1, ListNode head2) {
while (head1 != null && head2 != null) {
ListNode next1 = head1.next;
ListNode next2 = head2.next;
head1.next = head2;
head2.next = next1;
head1 = next1;
head2 = next2;
}
}
}