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

相关推荐
喵先生!2 小时前
C++中的vector和list的区别与适用场景
开发语言·c++
xMathematics3 小时前
计算机图形学实践:结合Qt和OpenGL实现绘制彩色三角形
开发语言·c++·qt·计算机图形学·cmake·opengl
yuanManGan5 小时前
C++入门小馆: 深入了解STLlist
开发语言·c++
梁下轻语的秋缘5 小时前
每日c/c++题 备战蓝桥杯(P1049 [NOIP 2001 普及组] 装箱问题)
c语言·c++·学习·蓝桥杯
逐光沧海5 小时前
STL常用算法——C++
开发语言·c++
wuqingshun3141595 小时前
蓝桥杯 5. 交换瓶子
数据结构·c++·算法·职场和发展·蓝桥杯
球求了6 小时前
C++:继承机制详解
开发语言·c++·学习
超爱笑嘻嘻6 小时前
shared_ptr八股收集 C++
c++
我想进大厂7 小时前
图论---朴素Prim(稠密图)
数据结构·c++·算法·图论
我想进大厂7 小时前
图论---Bellman-Ford算法
数据结构·c++·算法·图论