Reverse a singly linked list

The non-recursive way:

public ListNode reverse(ListNode head) {
        ListNode tail = null;
        while(head != null) {
            ListNode tmp = head.next;
            head.next = tail;
            tail = head;
            head = tmp;
        }
        return tail;
    }

The recursive way:

public ListNode reverse(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        //append the current head to the tail of the reversed list
        ListNode h = reverse(head.next);
        head.next.next = head; // tail points to head
        head.next = null;
        return h;
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s