leetcode——206.反转链表

本文详细介绍了LeetCode上两道经典链表题目的解法:递归与迭代方式实现链表反转。通过图文并茂的方式,清晰地阐述了每种方法的实现步骤和关键点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode链表相关题目

在这里插入图片描述

1、递归方法

如下图, 假如我们写的reverseList(head)方法的功能就是反转成功的结果;
在这里插入图片描述
reverseList(head.next)时如下图
在这里插入图片描述
在这里插入图片描述

如果reverseList(head.next)此时就已经反转了 1 -> 2 -> 3 -> 4 -> null, 如果要想成功反转为1 2 3 4 5 null, 我们只需要解决4.next -> 5, 5.next -> null, 这样就完成了反转

public class ListNode{
	int val;
	ListNode next;
	ListNode(int x) {
		val = x;
	}
}

class Solution {
	public ListNode reverseNode(ListNode head) {
		
		//if (head == null) return null;	  // 等同 return head
		//if (head.next == null) return head; // 此时就一个节点
		if (head == null || head.next == null)
			return head;
		
		// 此时的newNode就是节点4, 1 -> 2 -> 3 -> 4 -> null
		ListNode newNode = reverseNode(head.next) 
		// 此时要想办法将4的next指向5; 因为此时head指向5, head.next就指向4, head.next.next指向head即可
		// 也就是4.next指向5
		head.next.next = head;
		head.next = null;
		
		return newNode;
	}
}

这样就完成了递归反转链表;

2、迭代的方式

在这里插入图片描述

  • 因为题目中只提供了一个head指针, 所以我要想达到反转的效果, 就只能从head着手;
  • 首先提供一个newHead, 指向null, 我们期待的结果是最后返回的这个newHead指向1 -> 2 -> 3 -> 4 -> 5 -> null

在这里插入图片描述
在这里插入图片描述

思路 : 先让head指向newHead, 然后newHead指向head, 然后head指向它之前的next

一开始就要使用一个变量tmp来引用这head.next, 不然后面的节点都释放了
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

public class ListNode{
	int val;
	ListNode next;
	ListNode(int x) {
		val = x;
	}
}

class Solution {
	public ListNode reverseNode(ListNode head) {
	
		if (head == null || head.next == null) return head;
		
		ListNode newHead = null;
		while (head != null) {
			ListNode tmp = head.next; // tmp先指向head.next
			head.next = newHead;
			newHead = head;
			head = tmp;
		}
		return newNode;
	}
}

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
终止条件为head != null

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

white camel

感谢支持~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值