Tuesday, February 2, 2016

Reverse Singly Linked List

Question: Write a method to reverse singly linked list

Example:
Input: 1->2->3->4->5
Output: 5->4->3->2->1

Solution:
     /**
        * Reverse the linked list
        *
        */
       public void reverse(ListNode header)
       {
              ListNode prevNode, currNode, nextNode;
              prevNode = null;
              currNode = header.next;
              while(currNode != null) {
                     nextNode = currNode.next;
                     currNode.next = prevNode;
                     prevNode = currNode;
                     currNode = nextNode;
              }
              header.next = prevNode;

       }

No comments:

Post a Comment