My java solution,ask for your advice,is it good or bad, why?


  • 0
    H
     public ListNode reverseList(ListNode head) {
        if(head == null ) return null;
        ListNode old = new ListNode(0);
        old.next = head;
        ListNode dummy = new ListNode(0);
        dummy.next = null;
        ListNode p = head;
        while(p != null){
            old.next = p.next;
            p.next = dummy.next;
            dummy.next = p;
            p = old.next;
        }
        return dummy.next;
    }

  • 0
    C

    I think I understand your idea. You move a head node of original list A to tail of the new list B. My idea is the same as yours.
    But I think there is useless to new ListNode. If you initialize list B as null, there is no difference with your code.
    This is my code you can compare with yours
    https://leetcode.com/discuss/40640/my-iterative-solution-in-java-ac


  • 0
    H

    Thanks for your comment. I have read your code, I think it's much better than mine. But what is the difference between ① ListNode li = null and ② ListNode li = new ListNode(0), does ① cost less space.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.