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

相关推荐
阿闽ooo1 小时前
深入浅出适配器模式:从跨国插头适配看接口兼容的艺术
c++·设计模式·适配器模式
长安er1 小时前
LeetCode136/169/75/31/287 算法技巧题核心笔记
数据结构·算法·leetcode·链表·双指针
_w_z_j_2 小时前
最小栈(栈)
数据结构
fufu03112 小时前
Linux环境下的C语言编程(四十八)
数据结构·算法·排序算法
oioihoii3 小时前
跨越进程的对话之从管道到gRPC的通信技术演进
c++
爱装代码的小瓶子3 小时前
算法【c++】二叉树搜索树转换成排序双向链表
c++·算法·链表
思成Codes3 小时前
数据结构:基础线段树——线段树系列(提供模板)
数据结构·算法
阳洞洞4 小时前
cmake中如何从include_directories中移除某个特定的头文件
c++·cmake
墨雪不会编程4 小时前
C++【string篇1遍历方式】:从零开始到熟悉使用string类
java·开发语言·c++
蓝色汪洋5 小时前
经典修路问题
开发语言·c++·算法