Leetcode刷题笔记题解(C++):328. 奇偶链表

思路:遍历链表生成奇链表和偶链表,然后拼接两个链表生成新的链表。

cpp 复制代码
/**
 * 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) {
        ListNode* pre = new ListNode(-1);
        ListNode* pre_temp = pre;
        ListNode* end = new ListNode(-1);
        ListNode* end_temp = end;
        int i = 1;//用来判断奇偶
        while(head){
            if(i%2==1){
                pre_temp->next = head;
                pre_temp = pre_temp->next;
            }else{
                end_temp->next = head;
                end_temp = end_temp->next;
            }
            i++;
            head = head->next;
        }
        end_temp->next = nullptr;
        pre_temp->next = end->next;
        return pre->next;
    }
};
相关推荐
君义_noip1 小时前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
Ricky_Theseus1 小时前
静态链接与动态链接
c++
摸个小yu1 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
澈2071 小时前
双指针,数组去重
c++·算法
小辉同志2 小时前
207. 课程表
c++·算法·力扣·图论
CheerWWW2 小时前
深入理解计算机系统——位运算、树状数组
笔记·学习·算法·计算机系统
中屹指纹浏览器2 小时前
2026浏览器指纹检测技术演进与多账号反检测实战策略
经验分享·笔记
feng_you_ying_li2 小时前
C++11,{}的初始化情况与左右值及其引用
开发语言·数据结构·c++
skywalker_112 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
生信研究猿2 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展