Java AC code, may help u


  • 1
    Z
    /**
     * 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){
            return reverseList(head, null);
        }
    
        public ListNode reverseList(ListNode l, ListNode aim){
            if(l == null)
                return aim;
            ListNode node = new ListNode(l.val);
            node.next = aim;
            return reverseList(l.next, node);
        }
    
        /*another AC solution*/
        /*public ListNode reverseList(ListNode head) {
            ListNode next = null;
            while(head != null){
                ListNode temp = next;
                next = new ListNode(head.val);
                next.next = temp;
                head = head.next;
            }
            return next;
        }*/
    }

  • 1
    C
    public class Solution {
        public ListNode reverseList(ListNode head) {
            ListNode current = head;
            ListNode next = null;
            ListNode prev = null;
            
            while (current != null)
            {
                next = current.next;
                current.next = prev;
                prev = current;
                current = next;
            }
            return  prev;     
        }
    }

Log in to reply
 

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