Reverse Linked List

Reverse a singly linked list.

public class Solution {
    public ListNode reverseList(ListNode head) {
        if  (head == null)
            return head;
            
        if (head.next == null)
            return head; 
            
            
        ListNode header = new ListNode(0);
        header.next = head;
        
        ListNode cur = header.next; 
        while (cur.next != null) {
            ListNode nodeToMove = cur.next;
            ListNode afterHeader = header.next;
            ListNode afterAftercur = cur.next.next;
            cur.next = afterAftercur;
            header.next = nodeToMove;
            nodeToMove.next = afterHeader;
            
        }
        
        return header.next;
    }
}
Advertisements

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