题目
将给定的单链表L: L 0→L 1→…→L n-1→L n,
重新排序为: L 0→L n →L 1→L n-1→L 2→L n-2→…
要求使用原地算法,并且不改变节点的值
例如:
对于给定的单链表{1,2,3,4},将其重新排序为{1,4,2,3}.
Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.
思路
1、原地算法要求不使用或使用较少的存储空间完成算法要求。
2、本题思想,将链表分为两段,将后段的指针全部翻转,然后将两段链表中依次各取一个进行指向,直至两段链表的全部结点都被排列好。
3、本题三个重点,分别是取中函数,倒序函数以及各取一个结点连接过程。
注意点:在链表循环while中,判定条件会限制循环体中结点的指向情况。如倒序函数中,while(after!=null)将会限制循环体中after.next可以被取来使用或复制,但不保证pre.next,temp.next的有效性。
代码
/**
* 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