题解 | #重排链表#

重排链表

https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
import java.util.*;

public class Solution {
    public void reorderList(ListNode head) {
        // O(1): 翻转右半部分
        // O(n): 使用一个链表存储元素,逆序取
        if (head == null || head.next == null) {
            return;
        }
        ListNode n = head;
        ArrayList<ListNode> list = new ArrayList<>();
        while (n != null) {
            list.add(n);
            n = n.next;
        }

        // 交换
        int l = 0, r = list.size() - 1;
        while (l < r) {
            list.get(l).next = list.get(r);
            list.get(r).next = list.get(l + 1);
            l++;
            r--;
        }
        list.get(l).next = null;
    }
}

全部评论

相关推荐

仁者伍敌:服务员还要脱颖而出,这是五星级酒店吗
点赞 评论 收藏
分享
程序员饺子:正常 我沟通了200多个 15个要简历 面试2个 全投的成都的小厂。很多看我是27直接不会了😅
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务