LeetCode //C - 328. Odd Even Linked List

328. Odd Even Linked List

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 , 1 0 4 ] [0, 10^4] [0,104].
  • − 1 0 6 < = N o d e . v a l < = 1 0 6 -10^6 <= Node.val <= 10^6 −106<=Node.val<=106

From: LeetCode

Link: 328. Odd Even Linked List


Solution:

Ideas:

This function works by first checking if the head is NULL. If it's not, it creates two pointers, odd and even, which point to the first and second nodes of the list, respectively. evenHead stores the head of the even list.

The loop continues until there are no more even nodes or even nodes with a next node. Inside the loop, the odd nodes are connected to the next odd node, and similarly, the even nodes are connected to the next even node. After the end of the loop, the odd list and the even list are connected.

The final list starts with the odd nodes followed by the even nodes, as shown in your images.

Code:
c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* oddEvenList(struct ListNode* head) {
    if (head == NULL) return NULL;
    
    struct ListNode *odd = head;
    struct ListNode *even = head->next;
    struct ListNode *evenHead = even;

    while (even != NULL && even->next != NULL) {
        odd->next = odd->next->next;
        even->next = even->next->next;
        odd = odd->next;
        even = even->next;
    }
    
    odd->next = evenHead;
    return head;
}
相关推荐
刚入门的大一新生5 分钟前
归并排序延伸-非递归版本
算法·排序算法
独好紫罗兰9 分钟前
洛谷题单3-P1980 [NOIP 2013 普及组] 计数问题-python-流程图重构
开发语言·python·算法
独好紫罗兰14 分钟前
洛谷题单3-P1009 [NOIP 1998 普及组] 阶乘之和-python-流程图重构
开发语言·python·算法
曦月逸霜26 分钟前
蓝桥杯高频考点——高精度(含C++源码)
c++·算法·蓝桥杯
ゞ 正在缓冲99%…35 分钟前
leetcode152.乘积最大子数组
数据结构·算法·leetcode
CYRUS_STUDIO1 小时前
Frida Hook Android Native 函数
android·c语言·逆向
W说编程1 小时前
《UNIX网络编程卷1:套接字联网API》第5章 TCP客户服务器程序示例
c语言·网络·网络协议·tcp/ip·unix·tcp
闯闯爱编程1 小时前
数组与特殊压缩矩阵
数据结构·算法·矩阵
秋风战士1 小时前
通信算法之255:无人机频谱探测设备技术详解
算法·无人机
laimaxgg2 小时前
数据结构B树的实现
开发语言·数据结构·c++·b树·算法