It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Partner Sites
Board index Programming Java Forum

Reversing a linked structure recursively

Reversing a linked structure recursively

Postby Stiks on Fri Nov 02, 2007 8:37 pm

I'm attempting to reverse a linked list of integers recursively. in order to test my code, I'm doing unit test. Anyway, I can't get the list to reverse. I pretty much know why, and I have an idea of how it should work; however, I can't seem to put those thoughts into code. I think my problems start after the while loop. Here is what I have came up with so far:

Code: Select all
public static IntNode reverseLinks(IntNode head) {
      if (head == null) {
         return null;
      } else if (head.next == null) {
         return head;
      } else {
         IntNode temp = head;
         IntNode newNode = null;

         while (temp.next.next != null) {
            temp = temp.next;
         }
         newNode = new IntNode(temp.next.data);
         temp = null;
         return new IntNode(newNode.data, reverseLinks(temp));
      }
   }


IntNode is a class with two constructors, one which takes in the value, and the other takes in the value along with the next node.
Stiks
 
Posts: 7
Joined: Wed Apr 18, 2007 3:25 am

Return to Java Forum

Who is online

Users browsing this forum: No registered users and 0 guests