题解 | #链表的奇偶重排#

链表的奇偶重排

https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3

一种比较朴素的解决方案:奇偶分两条链后重新链接起来。

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 
 * @return ListNode类
 */
#include <stdlib.h>
struct ListNode* oddEvenList(struct ListNode* head ) {
    if(head == NULL){
        return head;
    }

    // write code here
    struct ListNode* p = head;
    struct ListNode* q = head->next;
    struct ListNode* resul = head; 
    //偶数
    struct ListNode* even = (struct ListNode*)malloc(sizeof(struct ListNode));
    even->next = NULL;
    struct ListNode* even_start = even;
    //奇偶分链
    while(p->next!=NULL&&q->next!=NULL){
        p->next = q->next;
        even->next = q;
        p = p->next;
        q = p->next;
        even = even->next;
    }
    //临界情况
    if(q!=NULL){
        even->next = q;
        even = even->next;
    }else{
        even->next = NULL;
    }
    p->next = even_start->next;
    return resul;
}

全部评论

相关推荐

2025-12-27 22:01
北京邮电大学 Java
坚持无悔意无休:北邮加粗放大
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务