2 Replies - 328 Views - Last Post: 10 March 2013 - 06:39 AM Rate Topic: -----

#1 Doughboy123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 02-October 12

Recursion Linked List

Posted 09 March 2013 - 11:10 PM

Hi all,

I want to write a method to recursively reverse a linked list.
I have been working on it for awhile but I haven't been able to get very far on it.

Here is the code I have so far:
public Node recursiveThisList(Node previous, Node current){
      if(previous == null)
          return null;
      if(previous.equals(head)){
          previous.setNext(null);
      }
      if(current == null){
          head = previous;
          return head;
      }else{
          Node temp = current.getNext();
          current.setNext(previous);
          reverseR(current, temp);
      } 
      return null;



Is there a way to do this with a void method and without any parameters: public void recursiveThisList().
Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: Recursion Linked List

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2198
  • View blog
  • Posts: 5,226
  • Joined: 10-September 10

Re: Recursion Linked List

Posted 10 March 2013 - 01:29 AM

A swapNode() method might be useful, then begin at one end, swap ends, move to next node, swap n + 1 with end - 1, and continue until reaching the middle. I would also include the word "reverse" in the title of your method.
Was This Post Helpful? 0
  • +
  • -

#3 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5796
  • View blog
  • Posts: 12,631
  • Joined: 16-October 07

Re: Recursion Linked List

Posted 10 March 2013 - 06:39 AM

View PostDoughboy123, on 10 March 2013 - 01:10 AM, said:

Is there a way to do this with a void method and without any parameters: public void recursiveThisList().


Not really. At least, not in your case. However, no rules against a method overload:
public void recursiveThisList() {
	recursiveThisList(head);
}

private void recursiveThisList(Node node){
	// your code here
}



That would be the recursive prototype, btw. You're making things much harder than they need be. Think about what recursion does for you: it goes one direction, then rolls back over it's foot steps. When you get to the bottom, where node.next is null, you have a new head. After that, you just add the nodes as you bubble back up.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1