您好,欢迎来到意榕旅游网。
搜索
您的当前位置:首页重排链表Java

重排链表Java

来源:意榕旅游网

将给定的单链表\ 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);
        
    }
   
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- yrrf.cn 版权所有 赣ICP备2024042794号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务