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

相关文章

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

C++读写word文档(.docx)DuckX库的使用详解

《C++读写word文档(.docx)DuckX库的使用详解》DuckX是C++库,用于创建/编辑.docx文件,支持读取文档、添加段落/片段、编辑表格,解决中文乱码需更改编码方案,进阶功能含文本替换... 目录一、基本用法1. 读取文档3. 添加段落4. 添加片段3. 编辑表格二、进阶用法1. 文本替换2

C++中处理文本数据char与string的终极对比指南

《C++中处理文本数据char与string的终极对比指南》在C++编程中char和string是两种用于处理字符数据的类型,但它们在使用方式和功能上有显著的不同,:本文主要介绍C++中处理文本数... 目录1. 基本定义与本质2. 内存管理3. 操作与功能4. 性能特点5. 使用场景6. 相互转换核心区别

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

C++ STL-string类底层实现过程

《C++STL-string类底层实现过程》本文实现了一个简易的string类,涵盖动态数组存储、深拷贝机制、迭代器支持、容量调整、字符串修改、运算符重载等功能,模拟标准string核心特性,重点强... 目录实现框架一、默认成员函数1.默认构造函数2.构造函数3.拷贝构造函数(重点)4.赋值运算符重载函数

C++ vector越界问题的完整解决方案

《C++vector越界问题的完整解决方案》在C++开发中,std::vector作为最常用的动态数组容器,其便捷性与性能优势使其成为处理可变长度数据的首选,然而,数组越界访问始终是威胁程序稳定性的... 目录引言一、vector越界的底层原理与危害1.1 越界访问的本质原因1.2 越界访问的实际危害二、基

Python学习笔记之getattr和hasattr用法示例详解

《Python学习笔记之getattr和hasattr用法示例详解》在Python中,hasattr()、getattr()和setattr()是一组内置函数,用于对对象的属性进行操作和查询,这篇文章... 目录1.getattr用法详解1.1 基本作用1.2 示例1.3 原理2.hasattr用法详解2.