题解 | #链表的奇偶重排#

链表的奇偶重排

https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3

思路

代码

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode oddEvenList(ListNode head) {
        // 健壮性检验
        if (head == null || head.next == null || head.next.next == null) {
            return head;
        }
        // 获取链表长度
        int length = count(head);
        int[] oldList = new int[length + 1];
        ListNode flag = head;
        // 将链表数据倒入数组中
        for (int i = 1; i <= length; i++) {
            oldList[i] = flag.val;
            flag = flag.next;
        }
        // 创建一个新数组
        int []newList = new int[length + 1];
        // 创建一个计数器
        int count = 1;
        // 奇数重排
        for (int i = 1; i <= length; i += 2) {
            newList[count] = oldList[i];
            count++;
        }
        // 偶数重排
        for (int i = 2; i <= length; i += 2) {
            newList[count] = oldList[i];
            count++;
        }
        flag = head;
        // 遍历数组,更新链表
        for (int i = 1; i <= length; i++) {
            flag.val = newList[i];
            flag = flag.next;
        }
        return head;
    }

    /**
     * 获取链表长度
     *
     * @param head 第一个数据节点
     * @return int 长度
     * @apiNote
     * @since 2022/12/21 9:52
     */
    public int count(ListNode head) {
        ListNode temp = head;
        int count = 1;
        while (temp.next != null) {
            temp = temp.next;
            count++;
        }
        return count;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 14:23
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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