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

408算法题leetcode--第13天

61. 旋转链表

  • 61. 旋转链表
  • 思路:注释
  • 时间:O(n);空间:O(1)
/*** 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* rotateRight(ListNode* head, int k) {// 思路1:和数组一样做三次翻转// 思路2:先连接尾节点和头节点成环,然后返回正数n-k+1个节点if(head == nullptr) return nullptr;int len = 1;ListNode* p = head;while(p->next){len++;p = p->next;}p->next = head;k %= len;// 移动n-k到目标节点的前一个节点p = head;for(int i = 0; i < len - k - 1; i++){p = p->next;}head = p->next;p->next = nullptr;return head;}
};

206. 反转链表

  • 206. 反转链表
  • 时间:O(n);空间:O(1)
/*** 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) {// 思路1:头插法// 思路2:两两互换ListNode *pre = nullptr, *cur = head, *temp = nullptr;while(cur){temp = cur->next;cur->next = pre;pre = cur;cur = temp;}return pre;}
};
http://www.lryc.cn/news/445088.html

相关文章:

  • 【MySQL】表的基本查询
  • 李宏毅2023机器学习HW15-Few-shot Classification
  • API安全推荐厂商瑞数信息入选IDC《中国数据安全技术发展路线图》
  • 1.5 计算机网络的性能指标
  • 【已解决】IDEA鼠标光标与黑块切换问题,亲测有效
  • 记一次sql查询优化
  • str函数的模拟(包括strn函数的模拟)
  • 畅阅读微信小程序
  • RHEL7(RedHat红帽)软件安装教程
  • CC 攻击:一种特殊的 DDoS 攻击
  • 掌上高考爬虫逆向分析
  • 忘了SD吧,现在是Flux的时代
  • 服务器安装openssh9.9p1
  • Spring Boot集成Redis Search快速入门Demo
  • 提升工作效率神器
  • 统信服务器操作系统【targetcli部署】
  • I2C中继器TCA9517A(TI)
  • 基于单片机的智能电话控制系统设计
  • Go 综合题面试题
  • 【Python报错已解决】AttributeError: ‘Tensor‘ object has no attribute ‘kernel_size‘
  • Spring MVC 参数校验 总结
  • 【图像压缩与重构】基于BP神经网络
  • 数据结构--单链表创建、增删改查功能以及与结构体合用
  • 开源ids snort (windows版)
  • 关于 vue3 axios的封装,并发请求相关
  • cpp中的namespace详解
  • request库的使用 | get请求
  • 理想低通信道和理想带通信道的区别
  • LAMP架构搭建
  • RT-DETR