P1【练习力扣203,206】【数据结构】【链表LinkedList】C++版

【203】 移除链表元素

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* removeElements(ListNode* head, int val) {
        ListNode* dummy = new ListNode(0, head);
        ListNode* temp = dummy;
        while(temp->next){
            if(temp->next->val == val){
                temp->next = temp->next->next;
            }else{
                temp = temp->next;
            }
        }

        return dummy->next;
    }
};

time:23:26

【206】反转链表

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* reverseList(ListNode* head) {
        ListNode* dummy_Node = new ListNode(0, head);
        while(head != NULL && head->next != NULL){
            ListNode* dnext = dummy_Node->next;
            ListNode* hnext = head->next;
            dummy_Node->next = hnext;
            head->next = hnext->next;
            hnext->next = dnext;  
        }
        
        return dummy_Node->next;
        
    }
};

time:30

总结:应理解dummy_Node的含义,指向头结点的哑节点。

相关推荐
郝学胜-神的一滴30 分钟前
[简化版 GAMES 101] 计算机图形学 08:三角形光栅化上
c++·unity·游戏引擎·godot·图形渲染·opengl·unreal
佳xuan35 分钟前
简而言之c++
c++·算法
屯子来了1 小时前
Windows + VS2022 + UE5.2 编译 Fast DDS 2.14.0 完整记录
c++·ue5·fastdds
YL200404261 小时前
027合并两个有序链表
java·数据结构·算法·链表
顶点多余1 小时前
自定义协议、序列化、反序列化实现
java·linux·开发语言·c++·tcp/ip
炽烈小老头1 小时前
【每天学习一点算法 2026/05/10】合并K个排序链表
学习·算法·链表
Bruce_kaizy1 小时前
c++ linux环境编程——从应用层到linux内核深入了解文件io的调用机制(爆肝)
linux·c++·c·嵌入式linux·文件io
Zephyr_01 小时前
java数据结构
java·数据结构
z200509302 小时前
C++中的右值引用
开发语言·c++
代码中介商2 小时前
C++文件流操作全解析
开发语言·c++