328. 奇偶链表

121 阅读1分钟

题目介绍

力扣328题:leetcode-cn.com/problems/od…

image.png

分析

使用两个哑结点preHead1preHead2分别对应奇节点的头节点的上一个节点以及偶节点的头节点的上一个节点,遍历整个链表,使用head1节点将整个链表的奇节点连接起来,使用使用head2节点将整个链表的偶节点连接起来,最后将奇链表跟偶数链表进行合并。

代码如下:

/**
 * 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) {
        if(head == null || head.next == null || head.next.next == null) {
            return head;
        }

        ListNode preHead1 = new ListNode(-1);
        ListNode preHead2 = new ListNode(-1);
        preHead1.next = head;
        preHead2.next = head.next;
        ListNode head1 = head;
        ListNode head2 = head.next;
        while(head1.next != null && head2.next != null) {
            //处理奇节点
            if(head1 != null && head1.next != null ) {
                head1.next = head1.next.next;
                head1 = head1.next;
            }

            //处理偶节点
            if(head2 !=null && head2.next != null) {
                head2.next = head2.next.next;
                head2 = head2.next;
            }
        }
        head1.next = preHead2.next;
        return preHead1.next;
    }
}

复杂度分析

  • 时间复杂度:O(n),其中 n 是链表的节点数。需要遍历链表中的每个节点,并更新指针。

  • 空间复杂度:O(1)。只需要维护有限的指针。