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

LCR 024

题目:LCR 024


解法一:迭代

每遍历一个节点,将该节点作为反转后的头节点,指向已返转的子链,需要注意最初遍历的节点为null,然后才是head节点
另外修改nextNode的指向时,应先保留nextNode原本的指向,用于传递给下次循环

    public ListNode reverseList1(ListNode head) {ListNode temp, reverseHead = null, nextNode = head;//A -> B -> Cwhile (nextNode != null) {temp = nextNode.next;nextNode.next = reverseHead;reverseHead = nextNode;nextNode = temp;}return reverseHead;}

解法二:递归

将每个待反转的链表分为头节点和子链,反转子链后,将子链的尾节点指向原来的头节点即可。

反转后的尾节点就是原子链的头节点,可以通过head.next获取。最后记得将原头节点指向null

    public ListNode reverseList(ListNode head) {if (head == null || head.next == null) return head;//A -> B <- CListNode reverseHead = reverseList(head.next);head.next.next = head;head.next = null;return reverseHead;}


http://www.mrgr.cn/news/27119.html

相关文章:

  • linux驱动开发-地址映射
  • I/O 多路复用:`select`、`poll`、`epoll` 和 `kqueue` 的区别与示例
  • 【python计算机视觉编程——10.OpenCV】
  • 滑动窗口算法—最小覆盖子串
  • java环境配置 | 基础铺垫
  • ​T​P​联​洲​一​面​
  • fly专享
  • 第T8周:猫狗识别
  • 计算机组成原理(第二次笔记)
  • Windows 环境下 vscode 配置 C/C++ 环境
  • pandas 将多条记录整合成一条记录,每条记录的year和month字段组成新的字段名
  • Java集合面试(上)
  • 查找算法--python
  • Makefile(超详细一文读懂)
  • 算法基础-扩展欧几里得算法
  • JS Web
  • python容器四之字典
  • GD - GD32350R_EVAL - PWM实验和验证3 - EmbeddedBuilder - 无源蜂鸣器 - 用PMOS来控制
  • 随机查询若干数据,并根据全部数据的点击量排序的核心代码
  • list和vector的区别