public Node reverse(Node one) { if (one == null) return null; if (one.next == null) return one; Node two = one.next; Node rest = reverse (two); Two.next = one; one.next = null; return rest.next; } code example

Example: reverse linked list in java to get both head and tail

/*
public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int x) { val = x; next = null; }
}
*/

public static ListNode[] reverse_linked_list(ListNode head) {

        ListNode prev = null;
        ListNode current = head;
        ListNode next;

        ListNode tail = head;

        while (current != null) {

            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }

        head = prev;

        ListNode[] result = {head, tail};

        return result;
}

Tags:

Java Example