题解 | 链表的奇偶重排

单链表的排序

https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08?tpId=295&tqId=1008897&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* oddEvenList(ListNode* head) {
        ListNode* head1 = new ListNode(-1); // 用于链接奇数位置的节点
        ListNode* head2 = new ListNode(-1); // 用于链接偶数位置的节点
        ListNode* cur1=head1;
        ListNode* cur2=head2;
        int flag = 1; // 1表示奇数位置,0代表偶数位置
        // 位置是奇偶交替的
        while(head){
            ListNode* next = head->next;
            head->next=nullptr;  // 断开原来奇数位置节点和偶数位置节点的指针关系
            if(flag==1){
                cur1->next=head;
                cur1=cur1->next;
                flag=0;
            }else{
                cur2->next=head;
                cur2=cur2->next;
                flag=1;
            }
            head=next;
        }
        cur1->next =head2->next;
        ListNode * result = head1->next;
        delete head1;
        delete head2;
        return result;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务