Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
Example
For example,
Given 1->2->3->4->null, reorder it to 1->4->2->3->null.
Given 1->2->3->4->null, reorder it to 1->4->2->3->null.
第一步,将链表分为两部分。时间O(n)
第二步,将第二部分链表逆序。时间O(n)
第三步,将链表重新组合。时间O(n)
总体时间O(n) 空间O(1)
总体时间O(n) 空间O(1)
public class Solution {
/**
* @param head: The head of linked list.
* @return: void
*/
public void reorderList(ListNode head) {
if (head == null || head.next == null){
return ;
}
ListNode mid = findmid(head);
ListNode tail = reverse(mid.next);
mid.next = null;
merge(head, tail);
}
private ListNode findmid(ListNode head){
ListNode slow = head;
ListNode fast = head.next;
while (fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode reverse(ListNode head){
ListNode prev = null;
while (head != null){
ListNode tem = head.next;
head.next = prev;
prev = head;
head = tem;
}
return prev;
}
private void merge(ListNode head, ListNode tail){
ListNode dummy = new ListNode(0);
while (head != null && tail != null){
dummy.next = head;
head = head.next;
dummy = dummy.next;
dummy.next = tail;
tail = tail.next;
dummy = dummy.next;
}
if (head != null){
dummy.next = head;
} else {
dummy.next = tail;
}
}
}
没有评论:
发表评论