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

标签 algorithm data-structures linked-list

我知道我的代码完全错误,但我不知道我哪里做错了,

谁能指出并解释我做错了什么?

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;
}

最佳答案

变化:

  1. head.next = null;//使列表末尾为空

  2. 当前.下一个 = 上一个;//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/

相关文章:

C 链表插入和显示功能不起作用

algorithm - 如何计算算法的运行时间?

algorithm - 存储间隔并允许快速删除的数据结构?

字符串的 SQL 数据类型

c - 固件中存储串口数据的数据结构

java - 在java中使用链表乘多项式

c - 对链表进行基数排序

algorithm - 在线性时间内准备数组以找到 O(k) 中的 k 个最小元素

algorithm - 计算给定特定输入大小的算法运行所需的时间

java - 尝试仅使用加法将两个数字相乘