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

链表的奇偶重排

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-08 14:08
点赞 评论 收藏
分享
人力小鱼姐:实习经历没有什么含金量,咖啡店员迎宾这种就别写了,其他两段包装一下 想找人力相关的话,总结一下个人优势,结合校园经历里有相关性的部分,加一段自我评价
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 11:55
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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