题解:
1、利用快慢指针寻找链表的中间节点 876(环形链表141)
2、反转链表 206
3、链表合并
solution:
class Solution {
public void reorderList(ListNode head) {
if(head==null) return;
ListNode mid=middleNode(head);
ListNode l1=head;
ListNode l2=mid.next;
mid.next=null;
l2=reverseList(l2);
mergeList(l1,l2);
}
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast!= null && fast.next!= null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode reverseList(ListNode head) {
ListNode prev = null;//前节点
ListNode curr = head;//当前节点
//每次循环,都将当前节点指向它前面的节点,然后当前节点和前节点后移
while (curr != null) {
ListNode nextTemp = curr.next;//临时节点,暂存当前节点的下一节点,用于后移
curr.next = prev;//将当前节点指向它前面的节点
//后移
prev = curr;
curr = nextTemp;
}
return prev;
}
//链表合并
public void mergeList(ListNode l1, ListNode l2) {
ListNode l1_tmp;
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;
}
}
}