uacs2024

导航

leetcode328-奇偶链表

328. 奇偶链表

 

首先是原始的错误代码。

第一处错误就是最后的p->next=head->next;      head->next其实早就不是一开始的第二个结点了,所以应该是事先保存的第二个结点

第二处错误就是while循环里的代码,不知道是什么原因出错

/**
 * 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||!head->next||!head->next->next)   return head;
        ListNode *p = head;
        ListNode *q = head->next;while(q&&q->next)
        {
            p->next=q->next;
q->next=q->next->next;
p=p->next;q=q->next;
} p->next=head->next; return head; } };

正确的代码

/**
 * 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||!head->next||!head->next->next)   return head;
        ListNode *p = head;
        ListNode *q = head->next;
        ListNode *evenHead = q;
        while(q&&q->next)
        {
            p->next=q->next;
            p=p->next;
            q->next=p->next;
            q=q->next;
        }
        //p->next=head->next;会报错
        //printf("%d",head->next->val);
        p->next=evenHead;
        return head;
    }
};

 

posted on 2022-09-15 16:13  ᶜʸᵃⁿ  阅读(9)  评论(0编辑  收藏  举报