Interview Question

Software Development Engineering Intern Interview Seattle, WA

Reverse a linked list.

Tags:
Answer

Interview Answer

3 Answers

0

public static Node reverse(Node n)
{
  if(n != null) {
    Node reversed.data = n.data;
    while(n.next != null)
    {
      Node insert;
      insert.data = n.next;
      insert.next = reversed;
      reversed = insert;
      n = n.next;
    }
    return reversed;
  }
  return null;
}

Interview Candidate on Jun 23, 2012
1

A recursive approach if anyone is interested. Only works for singly linked/non circular atm.
called like: reverse(head, null);

public static ListNode reverse(ListNode curr, ListNode prev) {
    if (curr == null) {
        return prev;
    } else {
        ListNode temp = curr.next;
        curr.next = prev;
        prev = curr;
        return reverse(temp, prev);
    }
}

IC2 on Jul 25, 2012
2

Node ReverseLinkedList(Node head)
{
    Node next = head.next;
    if (next == null)
    {
        return head;
    }

    Node revList = ReverseLinkedList(head.next);
    next.next = head;
    head.next = null;

    return revList;
}

Rob on Sep 22, 2012

Add Answers or Comments

To comment on this, Sign In or Sign Up.