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的含义,指向头结点的哑节点。

相关推荐
BK贝壳6 小时前
bool-hybrid-array 落盘我只认 .bha:用 Create_BHA / Ask_BHA 做布尔数组序列化
数据结构·python·numpy·1024程序员节
会编程的小孩6 小时前
C++ qt的安装
c++
?abc!9 小时前
(数组)581. 最短无序连续子数组
数据结构·算法·leetcode
小成2023032026512 小时前
C++~07补充
开发语言·c++
hold?fish:palm12 小时前
40 二叉树的直径
c++·leetcode
解决小子13 小时前
【虚幻引擎】【C++】【GAS框架】构建角色基类、属性集、数值钳制
c++·笔记·游戏引擎·虚幻·gas·能力系统
爱读书的小胖13 小时前
LeetCode 55 跳跃游戏 C 语言解题分析
c语言·数据结构·算法·leetcode·1024程序员节
舰长11514 小时前
将百万数据插入到 Redis,有哪些实现方案?
数据结构·redis·开源
lunar_coder14 小时前
【C++】如何解决智能指针的析构函数,如何实现shared_ptr的引用计数以及解决shared_ptr的循环引用
c++·1024程序员节
白白白小纯14 小时前
C++进阶.多态
c++