Day19: [LeetCode中等] 328. 奇偶链表

Day19: [LeetCode中等] 328. 奇偶链表

题源:

来自leetcode题库:

https://leetcode-cn.com/problems/odd-even-linked-list/

思路:

就是间隔性的把链表拆成两个,然后合并一下。

代码:

dirty code凑合看吧

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(!head||!(head->next)||!(head->next->next)) return head;
        ListNode *l1=NULL,*l2=NULL;
        ListNode *rear1=NULL,*rear2=NULL;
        auto p=head;
        bool ji=true;
        while(p){
            auto temp=p;
            p=p->next;
            temp->next=NULL;
            if(ji){
                ji=false;
                if(rear1) {
                    rear1->next=temp;
                    rear1=rear1->next;
                }
                else{
                    l1=temp;
                    rear1=temp;
                }
            }else{
                ji=true;
                if(rear2) {
                    rear2->next=temp;
                    rear2=rear2->next;
                }
                else{
                    l2=temp;
                    rear2=temp;
                }
            }
        }
        rear1->next=l2;
        return l1;
    }
};
发布了49 篇原创文章 · 获赞 13 · 访问量 545

猜你喜欢

转载自blog.csdn.net/qq2215459786/article/details/103165978