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}.
public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null) return;
ListNode mid = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
mid = mid.next;
}
mid.next = reverse(mid.next);
merge(head, mid, mid.next);
}
public static ListNode reverse(ListNode head) {
ListNode pre = head;
ListNode cur = head.next;
ListNode temp;
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
head.next = null;
return pre;
}
public static void merge(ListNode head1, ListNode end1, ListNode head2) {
ListNode cur1=head1;
ListNode cur2=head2;
ListNode temp1;
ListNode temp2;
while(cur1!=end1)
{
temp1=cur1.next;
cur1.next=cur2;
cur1=temp1;
temp2=cur2.next;
cur2.next=cur1;
cur2=temp2;
}
cur1.next=cur2;
}
}
1 遇到不好的思路要果断放弃,改其他的思路
2 参考代码有不好理解的,就自己写,浪费在读别人难懂代码的时间远比不上自己写来的快。
3 链表的永恒主题是每个节点在使用时,记得用temp存储它的下一个节点。