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

相关推荐
哈里谢顿9 小时前
跳表(Skip List):简单高效的有序数据结构
数据结构
xlp666hub14 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网15 小时前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub17 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
不想写代码的星星18 小时前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub1 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
任沫2 天前
字符串
数据结构·后端
不想写代码的星星2 天前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
祈安_2 天前
Java实现循环队列、栈实现队列、队列实现栈
java·数据结构·算法
不想写代码的星星3 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++