From 7d33e176b7e664f5429fbb3514e1fb08a53e61e9 Mon Sep 17 00:00:00 2001 From: dingjiachengcn <76956904+dingjiachengcn@users.noreply.github.com> Date: Wed, 26 Apr 2023 00:21:06 -0400 Subject: [PATCH] Create M 328. Odd Even Linked List --- M 328. Odd Even Linked List | 93 +++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 M 328. Odd Even Linked List diff --git a/M 328. Odd Even Linked List b/M 328. Odd Even Linked List new file mode 100644 index 0000000..3b3e530 --- /dev/null +++ b/M 328. Odd Even Linked List @@ -0,0 +1,93 @@ +Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. + +The first node is considered odd, and the second node is even, and so on. + +Note that the relative order inside both the even and odd groups should remain as it was in the input. + +You must solve the problem in O(1) extra space complexity and O(n) time complexity. + + + +Example 1: + + +Input: head = [1,2,3,4,5] +Output: [1,3,5,2,4] +Example 2: + + +Input: head = [2,1,3,5,6,4,7] +Output: [2,3,6,7,1,5,4] + + +Constraints: + +The number of nodes in the linked list is in the range [0, 10^4]. +-10^6 <= Node.val <= 10^6 + +题目翻译: +给定一个单链表的头节点,将所有奇数索引的节点组合在一起,后面是所有偶数索引的节点,并返回重新排序后的链表。 +第一个节点被认为是奇数,第二个节点是偶数,以此类推。 +注意,奇数和偶数组内的相对顺序应保持与输入时相同。 +你必须使用 O(1) 的额外空间复杂度和 O(n) 的时间复杂度来解决这个问题。 + +best answer: +class Solution { + public ListNode oddEvenList(ListNode head) { + // 如果链表为空或只有一个节点,则直接返回 + if (head == null || head.next == null) return head; + + // 初始化奇数链表头、尾节点,偶数链表头、尾节点 + ListNode oddHead = null, oddTail = null; + ListNode evenHead = null, evenTail = null; + ListNode curr = head; + int i = 1; + + // 遍历链表 + while (curr != null) { + // 生成奇数索引链表 + if (i % 2 == 1) { + if (oddHead == null) { + oddHead = curr; + oddTail = curr; + } else { + oddTail.next = curr; + oddTail = oddTail.next; + } + } + // 生成偶数索引链表 + else { + if (evenHead == null) { + evenHead = curr; + evenTail = curr; + } else { + evenTail.next = curr; + evenTail = evenTail.next; + } + } + // 更新当前节点为下一个节点 + curr = curr.next; + // 更新索引 + i++; + } + + // 偶数链表尾部的下一个节点应为空 + evenTail.next = null; + // 将偶数链表接在奇数链表尾部 + oddTail.next = evenHead; + + // 返回重新排序后的链表 + return oddHead; + } +} + +从算法的层面讲解这道题: + +如果链表为空或只有一个节点,则直接返回。 +初始化奇数链表头、尾节点,偶数链表头、尾节点。创建一个当前节点指针和索引变量。 +遍历链表,生成奇数索引链表和偶数索引链表。 +更新当前节点为下一个节点,索引加一。 +遍历完成后,将偶数链表的尾部指向空节点,将奇数链表的尾部指向偶数链表的头部。 +返回重新排序后的链表。 +这种解决方案的时间复杂度为 O(n),因为我们遍历了整个链表。空间复杂度为 O(1),因为我们只使用了几个额外的指针。 +