🌗 328. 奇偶链表

吞佛童子2022年10月10日
  • algorithm
  • List
小于 1 分钟

🌗 328. 奇偶链表

难度: 🌗

问题描述

img_3.png


解法

/**
 * 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 ListNode oddEvenList(ListNode head) {
        // 思路
        // 一次遍历链表,找到链表的尾节点,同时记录链表节点总个数
        // 从头开始,将 len/2 个链表节点 - 偶数节点 依次添加到尾部
        if(head == null || head.next == null || head.next.next == null) {
            return head;
        }
        // len >= 3
        int len = 1;
        ListNode tail = head;
        while(tail.next != null) {
            tail = tail.next;
            len ++;
        }
        int chg = len / 2; // 需要将 chg 个偶数节点移动到 tail 后面
        ListNode cur = head;
        for(int i = 0; i < chg; i ++) {
            ListNode next = cur.next;
            ListNode fur = next.next;
            // 需要将 next 移动到 tail 后面
            cur.next = fur;
            cur = fur;
            next.next = null;
            tail.next = next;
            tail = tail.next;
        }
        return head;
    }
}

输出

img_2.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou