C++刷题笔记(6)——leetcode203、707、206

2024-02-02 19:32

本文主要是介绍C++刷题笔记(6)——leetcode203、707、206,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

链表理论基础

1.list容器
2.关于链表,你该了解这些!
3.C++ list(STL list)容器完全攻略

题目1:203.移除链表元素

在这里插入图片描述
解题思路:
以链表 1 4 2 4 来举例,移除元素4。
在这里插入图片描述
但是如果删除的是头节点,移除头结点和移除其他节点的操作是不一样的,因为链表的其他节点都是通过前一个节点来移除当前节点,而头结点没有前一个节点,因此需要用新的方法:

解法一:设置一个虚拟头结点在进行删除操作

在这里插入图片描述
给链表添加一个虚拟头结点为新的头结点,移除这个旧头结点元素1。

在C++中还要从内存中删除移除后的节点

 class Solution {public:ListNode* removeElements(ListNode* head, int val) {ListNode* dummyHead = new ListNode(0);         // 初始化一个空节点,初始值为0,指针指向dummyheaddummyHead->next = head;                        // 将虚拟头结点指向head   上面两句也可以写成:ListNode* dummyHead = new ListNode(0,head)ListNode* cur = dummyHead;                     // 定义一个临时指针,等于虚拟头节点,用来代替虚拟头节点遍历链表(如果用虚拟头节点遍历链表,其值会不停变化,最后不好确定返回值)while (cur->next != NULL) {                    // 临时指针的下一个节点不为空if (cur->next->val == val) {               // 当指针的下一个节点的值等于目标值ListNode* tmp = cur->next;             //定义一个指针指向临时指针指向的节点(可以不写)cur->next = cur->next->next;           // 指针指向下下个值delete tmp;                            // 删除 cur->next}else {cur = cur->next;                       // 指针向后移动遍历指针}}head = dummyHead->next;                        // 重新定义头节点delete dummyHead;                              // 对虚拟头节点进的空间进行释放,防止内存泄漏return head;}};

解法二:直接使用原来的链表来进行删除操作

在这里插入图片描述
要将头结点向后移动一位
在这里插入图片描述
将原头结点从内存中删掉
在这里插入图片描述

 class Solution {public:ListNode* removeElements(ListNode* head, int val) {// 删除头结点,注意这里不是if,因为可能新的头节点指向的值也等于目标值while (head != NULL && head->val == val) { // 头节点不为空且头节点指向的值等于目标值ListNode* tmp = head;                  //定义一个指针指向临时指针指向的节点head = head->next;                     //使 头节点 指向 头节点的下一个delete tmp;                            //清理节点内存}// 删除非头结点ListNode* cur = head;                     //定义一个临时指针指向头节点while (cur != NULL && cur->next != NULL) {if (cur->next->val == val) {          //临时指针指向的节点的值 等于 目标值ListNode* tmp = cur->next;        //定义一个指针指向临时指针指向的节点(即要删除的节点)cur->next = cur->next->next;      //临时指针指向的节点 指向 目前临时指针指向的节点的下一个节点delete tmp;                       //清理节点内存}else {cur = cur->next;                  //没找到目标值,临时指针后移}}return head;}};

解法三:双指针法

评论区大佬给出了五种解法:移除链表元素(五种方法)
这里再记录一种双指针法,这位up也讲解的非常清晰:203.移除链表元素

题目2:707.设计链表

在这里插入图片描述

解法一:单链表

解题思路:
起始这一题看着很长,但主要还是那几行代码的堆叠,只要把那几行代码理解了就不难

以addAtIndex(index,val)为例:
假设链表为1->3->5->7->9,现在要在第2个节点之前插入一个新节点(addAtIndex(2,4))
在这里插入图片描述
那么首先新定义一个节点并赋值,然后将定义虚拟头节点指针
在这里插入图片描述
然后开始遍历index之前的链表:
在这里插入图片描述
然后执行newNode->next = cur->next;
在这里插入图片描述
执行cur->next = newNode;size++;
在这里插入图片描述
其他几种和这个也是差不多的
代码不难,但是要注意定义的临时指针cur什么时候指向虚拟头节点dummyhead、什么时候指向虚拟头节点的下一个节点dummyhead->next

 class MyLinkedList {public:// 定义链表节点结构体struct LinkedNode {int val;LinkedNode* next;LinkedNode(int val) :val(val), next(nullptr) {}  //构造函数};// 初始化链表MyLinkedList() {dummyHead = new LinkedNode(0);                   //定义虚拟头结点size = 0;                                        //链表长度}// 获取到第index个节点数值,如果index是非法数值直接返回-1, 注意index是从0开始的,第0个节点就是头结点int get(int index) {if (index > (size - 1) || index < 0) {           //输入的index不在范围内return -1;}LinkedNode* cur = dummyHead->next;               //当前指针指向真正头节点while (index--) {                                //遍历index前面的链表cur = cur->next;}return cur->val;}// 在链表最前面插入一个节点,插入完成后,新插入的节点为链表的新的头结点void addAtHead(int val) {LinkedNode* newNode = new LinkedNode(val);      //新建节点并赋值newNode->next = dummyHead->next;                //将虚拟头节点的指向赋值给新建节点的指向(即使新建节点的指向与虚拟头节点相同)dummyHead->next = newNode;                      //将虚拟头节点指向新建节点size++;}// 在链表最后面添加一个节点void addAtTail(int val) {LinkedNode* newNode = new LinkedNode(val);LinkedNode* cur = dummyHead;                   //从虚拟头节点开始,防止一开始是空链表while (cur->next != nullptr) {                 //遍历链表到最后位置cur = cur->next;}cur->next = newNode;                           //链表最后面添加一个节点size++;}//在第index个节点之前插入一个新节点,例如index为0,那么新插入的节点为链表的新头节点。//如果index 等于链表的长度,则说明是新插入的节点为链表的尾结点//如果index大于链表的长度,则返回空//void addAtIndex(int index, int val) {//    if (index <= 0) {//        addAtHead(val);//    }//    else if (index == size) {//        addAtTail(val);//    }//    else if (index > size) {//        return;//    }//    else {//        LinkedNode* newNode = new LinkedNode(val);//        LinkedNode* cur = dummyHead;//        while (index--) {//            cur = cur->next;//        }//        newNode->next = cur->next;//        cur->next = newNode;//        size++;//    }//}void addAtIndex(int index, int val) {if (index > size) {                            //大于链表长度返回空return;}     LinkedNode* newNode = new LinkedNode(val);     //包含了等于链表长度的情况LinkedNode* cur = dummyHead;while (index--) {cur = cur->next;}newNode->next = cur->next;cur->next = newNode;size++;}// 删除第index个节点,如果index 大于等于链表的长度,直接returnvoid deleteAtIndex(int index) {if (index >= size || index < 0) {return;}LinkedNode* cur = dummyHead;while (index--) {cur = cur->next;}LinkedNode* tmp = cur->next;cur->next = cur->next->next;delete tmp;size--;}// 打印链表void printLinkedList() {LinkedNode* cur = dummyHead;while (cur->next != nullptr) {cout << cur->next->val << " ";cur = cur->next;}cout << endl;}private:int size;LinkedNode* dummyHead;};

解法二:双链表

class ListsNode
{
public:int val;ListsNode* next;ListsNode* pre;ListsNode(int v, ListsNode* n, ListsNode* p):val(v),next(n),pre(p){}
};class MyLinkedList {
public:ListsNode* root;ListsNode* trail;int size;/** Initialize your data structure here. */MyLinkedList() {root=nullptr;trail=nullptr;size=0;}/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */int get(int index) {int temp=0;ListsNode* cur=root;while(cur!=nullptr){if(temp==index){return cur->val;}cur=cur->next;temp++;}return -1;}/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */void addAtHead(int val) {if(root!=nullptr){ListsNode* newNode=new ListsNode(val, root, nullptr);root->pre=newNode;root=newNode;         }else{root=new ListsNode(val, nullptr,nullptr);trail=root;}size++;}/** Append a node of value val to the last element of the linked list. */void addAtTail(int val) {if(trail!=nullptr){ListsNode* newNode = new ListsNode(val, nullptr, trail);trail->next=newNode;trail=newNode;}else{trail=new ListsNode(val, nullptr, nullptr);root=trail;}size++;}/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */void addAtIndex(int index, int val) {if(index<=0){addAtHead(val);return;}if(index==size){addAtTail(val);return;}int temp=0;ListsNode* pre=nullptr;ListsNode* cur=root;while(cur!=nullptr){if(temp==index){ListsNode* newNode=new ListsNode(val, cur, pre);if(pre!=nullptr){pre->next=newNode;}cur->pre=newNode;size++;return;}pre=cur;cur=cur->next;temp++;}}/** Delete the index-th node in the linked list, if the index is valid. */void deleteAtIndex(int index) {int temp=0;ListsNode* pre=nullptr;ListsNode* cur=root;if(index==0){ListsNode* old=root;root=root->next;if(root!=nullptr){root->pre=nullptr;}delete old;size--;return;}if(index==size-1){ListsNode* old=trail;trail=trail->pre;if(trail!=nullptr){trail->next=nullptr;}delete old;size--;return ;}while(cur!=nullptr){if(temp==index){ListsNode* old=cur;if(pre!=nullptr){pre->next=cur->next;}if(cur->next!=nullptr){cur->next->pre=pre;}delete old;size--;return;}pre=cur;cur=cur->next;temp++;}}
};

题目3:206.反转链表

在这里插入图片描述

解法一:双指针法

解题思路:
只需要将链表的next指针的指向翻转
在这里插入图片描述
定义两个指针,cur指针指向头节点、pre指针指向null空指针;
然后将cur->next指向pre,移动两个指针;
当cur指向null,翻转结束。

 class Solution {public:ListNode* reverseList(ListNode* head) {ListNode* temp;                        // 保存cur的下一个节点ListNode* cur = head;                  // cur指针指向头节点ListNode* pre = NULL;                  // pre指针指向nullwhile (cur) {                          // 遍历链表temp = cur->next;                  // 保存cur的下一个节点,因为接下来要改变cur->nextcur->next = pre;                   // 翻转操作// 更新pre 和 cur指针pre = cur;cur = temp;}return pre;}};

解法二:递归法

和双指针法的思路差不多

 class Solution {public:ListNode* reverse(ListNode* pre, ListNode* cur) {if (cur == NULL) return pre;ListNode* temp = cur->next;cur->next = pre;// 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步// pre = cur;// cur = temp;return reverse(cur, temp);}ListNode* reverseList(ListNode* head) {// 和双指针法初始化是一样的逻辑// ListNode* cur = head;// ListNode* pre = NULL;return reverse(NULL, head);}};

这篇关于C++刷题笔记(6)——leetcode203、707、206的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/671730

相关文章

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五

C++作用域和标识符查找规则详解

《C++作用域和标识符查找规则详解》在C++中,作用域(Scope)和标识符查找(IdentifierLookup)是理解代码行为的重要概念,本文将详细介绍这些规则,并通过实例来说明它们的工作原理,需... 目录作用域标识符查找规则1. 普通查找(Ordinary Lookup)2. 限定查找(Qualif

C/C++ chrono简单使用场景示例详解

《C/C++chrono简单使用场景示例详解》:本文主要介绍C/C++chrono简单使用场景示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友... 目录chrono使用场景举例1 输出格式化字符串chrono使用场景China编程举例1 输出格式化字符串示

C++/类与对象/默认成员函数@构造函数的用法

《C++/类与对象/默认成员函数@构造函数的用法》:本文主要介绍C++/类与对象/默认成员函数@构造函数的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录名词概念默认成员函数构造函数概念函数特征显示构造函数隐式构造函数总结名词概念默认构造函数:不用传参就可以

C++类和对象之默认成员函数的使用解读

《C++类和对象之默认成员函数的使用解读》:本文主要介绍C++类和对象之默认成员函数的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、默认成员函数有哪些二、各默认成员函数详解默认构造函数析构函数拷贝构造函数拷贝赋值运算符三、默认成员函数的注意事项总结一

C/C++中OpenCV 矩阵运算的实现

《C/C++中OpenCV矩阵运算的实现》本文主要介绍了C/C++中OpenCV矩阵运算的实现,包括基本算术运算(标量与矩阵)、矩阵乘法、转置、逆矩阵、行列式、迹、范数等操作,感兴趣的可以了解一下... 目录矩阵的创建与初始化创建矩阵访问矩阵元素基本的算术运算 ➕➖✖️➗矩阵与标量运算矩阵与矩阵运算 (逐元