LeetCode-328-奇偶链表-C语言

本文介绍了一种链表操作算法,通过创建两个临时链表分别存放原链表中的奇数位置和偶数位置节点,最后将这两个链表连接起来,实现链表的奇偶节点分离重组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

typedef struct ListNode Node;

/* 算法思想:
 * 生成两个临时链表,节点以奇偶分别添加到两个临时链表上;
 * 最后将两个临时链表链接起来并返回即可。
 *
 */
struct ListNode* oddEvenList(struct ListNode* head){
    Node node1, node2;
    node1.next = node2.next = NULL;
    Node *rear1 = &node1;
    Node *rear2 = &node2;
    Node *last;
    int i=0;
    
    while(head){
        last = head;
        head = head->next;
        
        if(i&1){
            rear2->next = last;
            rear2 = rear2->next;
            rear2->next = NULL;
        }else{
            rear1->next = last;
            rear1 = rear1->next;
            rear1->next = NULL;
        }
        
        i++;
    }
    
    rear1->next = node2.next;
    return node1.next;
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值