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++右移运算符的一个小坑及解决

《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.

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c

C++归并排序代码实现示例代码

《C++归并排序代码实现示例代码》归并排序将待排序数组分成两个子数组,分别对这两个子数组进行排序,然后将排序好的子数组合并,得到排序后的数组,:本文主要介绍C++归并排序代码实现的相关资料,需要的... 目录1 算法核心思想2 代码实现3 算法时间复杂度1 算法核心思想归并排序是一种高效的排序方式,需要用

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符