0
点赞
收藏
分享

微信扫一扫

2 Go语言的基础代码解析

程序猿不脱发2 2024-07-25 阅读 3

文章目录

1. 题目描述

在这里插入图片描述

2. 解题思路

  使用一个指针指向头部,然后再一次走两步,就可以遍历到奇数结点了,将其一一拷贝构造到一个新链表上即可。
  然后再指向头节点的下一个结点(可能为空,需要判断),重复上面的操作即可。注意:需要严格考虑循环的判断条件。

3. 代码实现

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* oddEvenList(ListNode* head) 
    {
        if(head == nullptr || head->next == nullptr) return head;
        auto newhead = new ListNode(-1);

        ListNode* cur = head, *ncur = newhead;
        while(cur)
        {
            ncur->next = new ListNode(cur->val);
            if(cur->next)
                cur = cur->next->next;
            else
                cur = nullptr;
            ncur = ncur->next;
        }

        cur = head->next;
        while(cur)
        {
            ncur->next = new ListNode(cur->val);
            if(cur->next)
                cur = cur->next->next;
            else
                cur = nullptr;
            ncur = ncur->next;
        }
        return newhead->next;
    }
};
举报

相关推荐

0 条评论