Open songyy5517 opened 6 months ago
Approach: Two Pointers
Complexity Analysis
/**
* 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) {
// Intuition: Two pointers
// 1. Exception handling
if (head == null || head.next == null)
return head;
// 2. Define two pointers
ListNode p1 = head, p2 = head.next, p2_head = head.next;
// 3. Loop through the linked list
while (p1.next != null && p1.next.next != null){
p1.next = p2.next;
p1 = p1.next;
p2.next = p1.next;
p2 = p2.next;
}
// 4. Concatenate the head of the odd list and the rear of the even list
p1.next = p2_head;
return head;
}
}
2024/5/27
while (p_even != null && p_even.next != null)
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:
Example 2:
Intuition Essentially, the problem is to split the whole linked list into two sub-linked list. A straightforward idea is to use two pointers to split the linked list when looping it. Finally, concatenate the two linked list and return it.