关于单向链表反转问题空指针情况

文章讨论了在尝试反转单向链表时遇到的NullPointerException问题。问题源于未检查head是否为null。解决方案是在开始时添加条件判断,确保当头节点为空时返回null。修复后的代码避免了错误,提高了代码的健壮性。
摘要由CSDN通过智能技术生成

问题描述

提示:这里描述项目中遇到的问题:

对单向链表进行反转,代码:

@Override
	public static Node reverseLinkedList2(Node head) {
		Node pre = null;
		Node next = null;
		next = head.next;
		while(head.next != null){
			head.next = pre;
			pre = head;
			head = next;
			next = head.next;
		}
		head.next = pre;
		return head;
	}

报错信息:
在这里插入图片描述Exception in thread “main” java.lang.NullPointerException

网上搜了搜,基本就是建议我声明next和pre指针的时候进行初始化,即pre = new Node()但是由于我给Node的定义是Node的value部分必须为int,而这个地方我需要将pre指向null,这就会变得非常麻烦。


原因分析:

提示:这里填写问题的分析:

这个地方报的这个错可以理解为在链表为某种情况下,调用了null的next而导致的报错,仔细考虑会发现如果head一开始指向的就是null,这个代码就一定会报错


解决方案:

提示:这里填写该问题的具体解决方案:

正确代码:

	public static Node reverseLinkedList2(Node head) {
		if(head == null){
			return head;
		}
		Node pre = null;
		Node next = null;
		next = head.next;
		while(head.next != null){
			head.next = pre;
			pre = head;
			head = next;
			next = head.next;
		}
		head.next = pre;
		return head;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值