LeetCode 328 奇偶链表

基本思路,找到奇节点链表,偶节点链表,然后串联

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(!head){
            return head;
        }
        if(!head->next){
            return head;
        }
        ListNode *h;
        h=head;//保存首个节点用于返回
        
        ListNode *temp;
        temp=head->next;//保存奇节点首个节点
        ListNode *odd;
        odd=head->next;//奇节点首个节点
        while(odd&&odd->next){//结束条件
              head->next=odd->next;//找下一个偶节点
              head=head->next;
              odd->next=head->next;//找下一个奇节点
              odd=odd->next;
              
        }
        head->next=temp;
        return  h;
    }
};
原文地址:https://www.cnblogs.com/zzw-/p/13268093.html