Write and test a recursive Java method that reverses a singl

Write and test a recursive Java method that reverses a singly linked list so that the ordering of the nodes becomes opposite of what it was before. (Please submit your code. Please also include the displayed results of running the method in a separate word document.)

Solution

Program:

public class SinglyList

{

static node head;

static class node

{

int data;

Node next;

Node(int a)

{

data = a;

next = null;

}

}

Node reverse(Node node)

{

Node previous = null;

Node current = node;

Node next = null;

while ( current !=null)

next = current .next;

current.next = previous;

previous = current;

current = next;

}

node = previous;

return node;

}

void printList(Node node)

while(node !=null)

{

System.out.println(node.data + \" \");

node = node.next;

}

}

public static void main(String [] args )

{

SinglyList list = new SinglyList();

list.head= new Node(74);

list.head.next= new Node(80);

list.head.next.next= new Node(87);

list.head.next.next.next= new Node(28)

list.head.next.next.next.next= new Node(83);

System.out.println(\"The singly linked list is:\");

list.printList(head);

head=list.reverse(head);

System.out.println(\" \");

System.out.println(\"the reversed singly linked list is:\");

list.printList(head);

}

}

Output:

The singly linked list is:

74 80 87 28 83

The reversed singly linked list is:

83 28 87 80 74   

 Write and test a recursive Java method that reverses a singly linked list so that the ordering of the nodes becomes opposite of what it was before. (Please sub
 Write and test a recursive Java method that reverses a singly linked list so that the ordering of the nodes becomes opposite of what it was before. (Please sub

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site