当前位置: 首页 > news >正文

链表学习之反转链表

链表解题技巧

  • 额外的数据结构(哈希表);
  • 快慢指针;
  • 虚拟头节点;

反转链表

分别实现单向链表和双向链表的反转。

要求:长度为N的链表,时间复杂度为O(N),额外空间复杂度为O(1)。

反转单向链表:

方法1(使用栈,时:O(N),空:O(N)):

  1. 第一次遍历将数据添加至栈中;
  2. 定义一个空节点,tmp记录,cur指向该节点;
  3. 栈不为空开始循环出栈:
    1. cur的next指向的栈顶元素;
    2. 栈顶元素出栈;
    3. cur移动到next的位置;
  4. cur现在在最后一个位置,将其next赋值为nullptr;
  5. cur指向tmp(空节点)的next位置,并删除tmp;
  6. 返回cur(新的头节点);
LinkedNode* LinkedList::reverseWithStack(LinkedNode *head) {if (head == nullptr || head->next == nullptr) {return head;}std::stack<LinkedNode*> stk;LinkedNode* cur = head;while (cur) {stk.push(cur);cur = cur->next;}LinkedNode* tmp = new LinkedNode();cur = tmp;while (!stk.empty()) {cur->next = stk.top();stk.pop();cur = cur->next;}cur->next = nullptr;cur = tmp->next;delete tmp;return cur;
}

方法2(双指针,时:O(N),空:O(1)):

双指针解法:

  1. 定义两个指针new_head,cur,初始new_head指向head,cur指向head的next;
  2. cur不为nullptr则开始循环:
    1. head的next赋值为cur的next;
    2. cur的next赋值为new_head;
    3. new_head移动到cur;
    4. cur移动到head的next;
  3. 最后返回new_head即可。
LinkedNode* LinkedList::reverse(LinkedNode *head) {if (head == nullptr || head->next == nullptr) {return head;}LinkedNode *new_head = head;LinkedNode *cur = head->next;while (cur) {head->next = cur->next;cur->next = new_head;new_head = cur;cur = head->next;}return new_head;
}

反转双链表

DoubleLinkedNode* LinkedList::reverseDoubleLinkedList(DoubleLinkedNode *head) {if (head == nullptr || head->next == nullptr) {return head;}DoubleLinkedNode *pre = head;DoubleLinkedNode *cur = head->next;while (cur) {DoubleLinkedNode *tmp = pre->next;pre->next = pre->pre;pre->pre = tmp;pre = cur;cur = cur->next;}return pre;
} 
http://www.lryc.cn/news/11338.html

相关文章:

  • ONNXRUNTUIME实例分割网络说明
  • 几行代码,就写完懒加载啦?
  • PyTorch常用的损失函数(ChatGPT)
  • LeetCode——1237. 找出给定方程的正整数解
  • 系统编程中的进程的概念No.3【进程状态】
  • 推荐 3 款 Golang 语义化版本库
  • Windows平台使用gdb连接qemu虚拟机上的系统
  • 【博客624】MAC地址表、ARP表、路由表(RIB表)、转发表(FIB表)
  • 【蓝桥日记⑤】2014第五届省赛(软件类)JavaA组❆答案解析
  • Leetcode.1139 最大的以 1 为边界的正方形
  • Bing+ChatGPT 对传统搜索引擎的降维打击
  • 【JS】数组常用方法总结-功能、参数、返回值
  • pytest 单元测试前后置处理
  • 汽车安全硬件扩展 AUTOSAR SHE SecureHardwareExtensions
  • 2023年美国大学生数学建模C题:预测Wordle结果建模详解+模型代码
  • 5、HAL库驱动W25Qxx
  • git rebase 洐合(变基)
  • Kubernetes 1.18学习笔记
  • AJAX技术
  • 华为OD机试 - 最大排列(JS)
  • Prometheus Docker安装及监控自身
  • 点云处理PCL常用函数与工具
  • FyListen 在 MVP 架构中的内存优化表现
  • Qt代码单元测试以及报告生成
  • vscode构建Vue3.0项目(vite,vue-cli)
  • 【2023】华为OD机试真题Java-题目0215-优雅数组
  • 通过Prowork每日自动提醒待处理工作任务
  • Linux自定义系统服务
  • mongodb lambda 查询插件
  • C++设计模式(16)——责任链模式