从OJ题“反转链表”理解链表

本文详细解析了牛客网《剑指offer》中反转链表的题目,通过Java代码实现并配合测试用例进行解释。代码中,通过while循环不断更新节点的next指针,最终完成链表的反转。解读了代码每一步如何操作链表节点,帮助读者理解链表反转的过程。

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

1 题目

1、题目来自于牛客网:《剑指offer》反转链表
2、如图所示:
在这里插入图片描述

2 题解代码

1、注意:
1)此处不对原因进行阐述,而是对链表进行更形象的理解。
2)上述牛客网的链接可以在不写main函数的情况下,对代码进行调试,若有不懂可以进行调试,以获得更加形象的认识。

2、Java代码:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode newHead = null;
        ListNode temp;
        while(head != null) {
            temp = head.next;

            head.next = newHead;

            newHead = head;

            head = temp;
        }
        return newHead;
    }
}

3、测试用例:1->2->3->null
(1)第1次进入while循环:
0)head:1->2->3->null
1)temp = 2->3->null; temp:2->3->null
2)head.next = null; head:1->null
3)newHead = 1->null; newHead:1->null
4)head = 2->3->null; head:2->3->null

(2)第2次进入while循环:
0)head:2->3->null
1)temp = 3->null; temp:3->null
2)head.next = 1->null; head:2->1->null
3)newHead = 2->1->null; newHead:2->1->null;
4)head = 3->null; head:3->null;

(3)第3次进入while循环:
0)head:3->null;
1)temp = null; temp:null
2)head.next = 2->1->null; head:3->2->1->null
3)newHead = 3->2->1->null; newHead:3->2->1->null
4)head = null; head:null

(4)head=null,不进入while,结束!

4、解读:
1)temp = head.next;——将head的next赋值给temp(将head链表,除了当前的节点head,都赋值给temp)。
2)head.next = newHead;——head的下一个节点(指向)newHead。

5、如有不当之处,还请大佬指正,感谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值