a big mystery: reversing a linked list

15.03.2009

when you interview for a job position in a software company, -i have no frakking idea why- they always ask this question, reversing a linked list. i guess it's the greatest mystery in computer programming. software companies name changes, but the question remains.

easiest way to reverse a linked list is to create new head pointer, iterate through the list take the item from the list and add it to the front of the list.

here's the full code in java.
  class Node {
    int data;
    Node next;
    
    public Node(int data) {
      this.data = data;
      this.next = null;
    }
  }
  
  class LinkedList {
    private Node head;
    
    public LinkedList() {
      this.head = null;
    }
    
    public void reverse() {
      Node cur = head;
      head = null;
      while(cur != null) {
        Node temp = cur;
        cur = cur.next;
        temp.next = head;
        head = temp;
      }
    }
    
  }

if you're interested in more methods of linked lists, you may want to read these posts as well:

blog comments powered by Disqus