首页 > 解决方案 > 关于反向链表的问题(leetcode 206)

问题描述

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

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

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

标签: algorithmdata-structureslinked-list

解决方案


变化:

  1. 头。下一个=空;// 使列表的末尾为空

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

推荐阅读