当前位置:网站首页>刷题记录----反转链表(反转整个链表)
刷题记录----反转链表(反转整个链表)
2022-07-28 05:26:00 【HandsomeDog_L】
目录
两个指针,pre和cur,cur代替头节点遍历链表,过程中用next记录下cur.next
题目描述:给定一个链表,反转并返回新的头节点
迭代:
两个指针,pre和cur,cur代替头节点遍历链表,过程中用next记录下cur.next
ListNode reverse(ListNode head) {
ListNode pre = null, cur = head;
while (cur != null) {
ListNode next = cur.next;//记录下一个节点
cur.next = pre;//改变第一个节点的指向
pre = cur;//前驱节点更新为当前节点
cur = next;//向后更新节点
}
return pre;
}递归:
public ListNode reverseList(ListNode head) {
return reverse(null, head);
}
private ListNode reverse(ListNode prev, ListNode cur) {
if (cur == null) {
return prev;
}
ListNode temp = null;
temp = cur.next;// 先保存下一个节点
cur.next = prev;// 反转
// 更新prev、cur位置
// prev = cur;
// cur = temp;
return reverse(cur, temp);
}递归:从后往前反转
把head.next以后的节点看成一个节点
ListNode reverseList(ListNode head) {
// 边缘条件判断
if(head == null) return null;
if (head.next == null) return head;
// 递归调用,翻转第二个节点开始往后的链表
ListNode last = reverseList(head.next);
// 翻转头节点与第二个节点的指向
head.next.next = head;
// 此时的 head 节点为尾节点,next 需要指向 NULL
head.next = null;
return last;
} 边栏推荐
猜你喜欢

MFC 使用控制台打印程序信息

clickhouse聚合之探索聚合内部机制

VI and VIM commands

How many columns are the most suitable for Clickhouse to build a width table?

Word自动目录字体修改和行间距的问题

Filter

Matlab simulation of radar imaging 3 - multi-target detection

EMC experiment practical case ESD electrostatic experiment

解决内存占用比应用进程占用高的问题

2022年七夕礼物推荐!好看便宜又实用的礼物推荐
随机推荐
Perl introductory learning (VIII) subroutine
2022-05-15 基于jwt令牌token
Getting started with hugging face
The startup fails when switching Chinese when using wampserver3.2.6
藏宝计划TPC系统开发Dapp搭建
mysql删表不删库
Matlab simulation of radar imaging 3 - multi-target detection
Perl Introduction (10) formatted output
2022-07-17 达梦数据库安装
Antenna effect solution
error: redefinition of ‘xxx‘
空气传导耳机哪个牌子好、备受好评的气传导耳机推荐
七夕礼物送女生什么好?颜值在线又有心意的礼物推荐
【学习笔记】线程创建
Find the network address and broadcast address of the host according to the IP address and subnet mask
qt中Qthread线程的使用以及安全关闭
mysql join技巧
气导贴耳式耳机推荐、不需要佩戴入耳的气传导耳机
【学习笔记】编码能力
2022年七夕礼物推荐!好看便宜又实用的礼物推荐