• RSS
  • Facebook
  • Twitter

Knowledge is Power.

  • Who you are ?

    Working on machines without understanding them ? Then you should be here..

  • Where you are ?

    Geographical location should not become a barrier to Share our knowledge.

  • What do you do ?

    Puzzles and Interview question are intended to be discussed here.

    Sunday, February 21, 2010

    The question is like this – if you have a linked list that holds 1 -> 2 -> 3 -> 4 -> X, then after the function has been called the linked list would hold 2 -> 1 -> 4 -> 3 -> X.

    Solution :

    public void reversePairRecursive(Node n)
    {
    int temp;
    if(n==null || n.next ==null)
    return; //base case for empty or 1 element list
    else
    {
    //Reverse first pair
    temp = n.data;
    n.data = n.next.data;
    n.next.data = temp;

    //Call the method recursively for the rest of the list
    reversePairRecursive(n.next.next);
    }

    }
    /**
    * Reverse the linkedlist in pairs -Iterative version
    * @param n
    */
    public void reversePairIterative()
    {
    Node current = head;
    int temp;

    while(current != null && current.next != null)
    {
    //Swap the pair
    temp = current.data;
    current.data = current.next.data;
    current.next.data= temp;

    //Advance the current pointer twice
    current = current.next.next;
    }
    }

    0 comments:

    Post a Comment