题目分析
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
这道题目涉及到快慢指针找中心位置,链表逆序,链表合并。
代码
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null) {
return;
}
// 快慢指针找到中点
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
fast = slow.next;
slow.next = null;
// 翻转后半部分
// 插入法
// 哑结点
ListNode dummy = new ListNode(0);
ListNode temp = null;
while(fast != null) {
temp = dummy.next;
dummy.next = fast;
fast = fast.next; // fast 指针后移
dummy.next.next = temp;
}
// 合并
ListNode temp1 = head;
ListNode temp2 = head.next;
temp = dummy.next;
while(temp != null && temp2 != null) {
temp1.next = temp;
temp = temp.next;
temp1.next.next = temp2;
temp1 = temp1.next.next;
temp2 = temp2.next;
}
temp1.next = temp;
}
}
网友评论