LetCode: Reverse Linked List

// Reverse a singly linked list.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class ReverseLinkedList {
    public ListNode reverseList(ListNode head) {
        if(head == null) {
            return head;
        }
 
        ListNode newHead = null;
     
        while(head != null) {
            ListNode next = head.next;
            head.next = newHead;
            newHead = head;
            head = next;
        }
     
        return newHead;
    }

public ListNode getReversedRecursive(ListNode newroot, ListNode root){
if(newroot==null){
return root;
}
ListNode temp = new ListNode(newroot.val);
temp.next = root;
return getReversedRecursive(newroot.next, temp);
}
}

No comments:

Post a Comment