反向链接列表Java内存 [英] Reverse Linked list Java memory

查看:62
本文介绍了反向链接列表Java内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当时正在解决这个leetcode问题,但我不明白为什么该解决方案不起作用.似乎只返回head元素.谢谢

I was doing this leetcode problem and I don't understand why this solution doesn't work. It seems to only be returning the head element. Thanks

 /**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {       
        ListNode curr = null;
        ListNode lst = null;
        while (head != null)
        {
            curr = head;
            curr.next = lst;
            lst = curr;
            head = head.next;
        }

        return curr;

    }
}

推荐答案

稍微了解一下Java中的引用和对象. Java总是传递引用的副本.因此,当您这样做时,

Read about reference and object in java little bit. Java always passes copy of reference. So when you do,

 curr = head;

curr和head指向同一对象.当你这样做的时候,

curr and head point to same object. And when you do,

 curr.next = lst;

curr.next和head.next都开始指向null(第一个为null). 下次您会中断循环.

Both curr.next as well as head.next both starts pointing to null (as lst in null). And you loop breaks next time.

尝试此解决方案将起作用.

Try this solution it will work.

public class Solution {
    public ListNode reverseList(ListNode head) {       
        ListNode nxt = null;
        ListNode lst = null;
        while (head != null)
        {
            nxt = head.next;
            head.next = lst;
            lst = head;
            head = nxt;
        }
        return lst;
    }
}

这篇关于反向链接列表Java内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆