LCR 026. 重排链表

LCR 026. 重排链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        // 将所有节点存入列表中,因为链表是单向的,没法倒序往回找,所以必须存列表中
        List<ListNode> cache = new ArrayList<>();
        while(head!=null){
            cache.add(head);
            head = head.next;
        }

        int l=0;
        int r = cache.size()-1;

        // 需要找到中点位置断开,所以需要分奇偶
        if(cache.size()%2==0){
            cache.get((l+r)/2+1).next = null;
        }else{
            cache.get((l+r)/2).next = null;
        }

        // 修改左右指针所指节点的指向
        while(l+1<r){
            cache.get(l).next = cache.get(r);
            cache.get(r).next = cache.get(l+1);
            l++;
            r--;
        }
    }
}

学习:https://www.bilibili.com/video/BV1Bu411G7uJ/?spm_id_from=333.337.search-card.all.click&vd_source=46d50b5d646b50dcb2a208d3946b1598

作者:静默虚空
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。

posted @   Chenyi_li  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示