将给定的单链表\ L L: L_0→L_1→…→L_{n-1}→L_ nL0→L1→…→Ln−1→Ln
重新排序为:L_0→L_n →L_1→L_{n-1}→L_2→L_{n-2}→…L0→Ln→L1→Ln−1→L2→Ln−2→…
要求使用原地算法,不能只改变节点内部的值,需要对实际的节点进行交换。
数据范围:链表长度 0 \le n \le 200000≤n≤20000 ,链表中每个节点的值满足 0 \le val \le 10000≤val≤1000
要求:空间复杂度 O(n)O(n) 并在链表上进行操作而不新建链表,时间复杂度 O(n)O(n)
进阶:空间复杂度 O(1)O(1) , 时间复杂度 O(n)O(n)
示例1
输入:
{1,2,3,4}
复制返回值:
{1,4,2,3}
复制说明:
给定head链表1->2->3->4, 重新排列为 1->4->2->3,会取head链表里面的值打印输出 1
示例2
输入:
{1,2,3,4,5}
复制返回值:
{1,5,2,4,3}
复制说明:
给定head链表1->2->3->4->5, 重新排列为 1->5>2->4->3,会取head链表里面的值打印输出
示例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||head.next.next==null)return ;
ListNode temp=head;
do{
temp=temp.next;
}while(temp.next.next!=null);
ListNode tail=temp.next;
temp.next=tail.next;
tail.next=head.next;
head.next=tail;
head=tail.next;
reorderList(head);
}
}