Reverse Linked List

Reverse a singly linked list.

Code:

Iteratively:

public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        while (head.next != null) {
            ListNode temp = head.next;
            head.next = head.next.next;
            temp.next = dummy.next;
            dummy.next = temp;
        }
        return dummy.next;
    }
}

Recursively:

public ListNode reverseList(ListNode node) {
    if (node == null || node.next == null) return node;

    ListNode next = node.next;
    ListNode head = reverseList(next);
    next.next = node;
    node.next = null;
    return head;
}

results matching ""

    No results matching ""