gpt4 book ai didi

algorithm - 关于反向链表的问题(leetcode 206)

转载 作者:行者123 更新时间:2023-12-04 01:14:54 26 4
gpt4 key购买 nike

我知道我的代码完全错误,但我不知道我哪里做错了,
谁能指出并解释我做错了什么?

public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}

ListNode prev = null;
ListNode current = head;
ListNode nextNode = head.next;

while (nextNode != null) {
prev = current;
current = nextNode;
current.next = prev;
nextNode = nextNode.next;
System.out.println(nextNode.val);
}

return current;
}

最佳答案

变化:

  • head.next = null;//使列表的末尾为空
  • current.next = 上一个;//current 是对节点的引用,因此对它的更改也会更改引用 nextNode 的节点
    public ListNode reverseList(ListNode head) {
    if (head == null) {
    return head;
    }

    ListNode prev = null;
    ListNode current = head;
    ListNode nextNode = head.next;
    head.next = null; // to make the end of the list as null

    while (nextNode != null) {
    prev = current;
    current = nextNode;
    nextNode = nextNode.next; // first get next node, before ...
    current.next = prev; // ... overwriting it here
    // System.out.println(nextNode.val);
    }

    return current;
    }
  • 关于algorithm - 关于反向链表的问题(leetcode 206),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63666299/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com