题解 | #链表的奇偶重排#
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
思路
- 参照BM13. 判断一个链表是否为回文结构
- 创建一个数组,将链表的数据倒入旧数组中,按位序奇偶分别装入新数组,最后再将数据赋给老链表,返回即可
代码
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;
    }
}
 投递华为等公司10个岗位
投递华为等公司10个岗位