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

/**
 * 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;
    
}


猜你喜欢

转载自blog.csdn.net/weixin_36094222/article/details/90045728