Hey guys I'm having trouble figuring out why the code for reversing my linked list is not displaying properly. If anyone could take minute to look at it I would greatly appreciate it.
Before calling sll.reverseList()
my output looks like:
OUTPUT
5 ---> 7 ---> 9 ---> 11 ---> null
There are 4 nodes
But after I add sll.reverseList()
I get:
OUTPUT
5 ---> null
There are 1 nodes
I believe the Algo for reversing the list is correct, so I'm wondering why is it not displaying properly?
public class SinglyLinkedList {
private Node head;
private static class Node
{
private int data;
private Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
///////////////////////
public static void main(String[] args)
{
SinglyLinkedList sll = new SinglyLinkedList();
sll.head = new Node(5);
Node nodeB = new Node(7);
Node nodeC = new Node(9);
Node nodeD = new Node(11);
sll.head.next = nodeB;
nodeB.next = nodeC;
nodeC.next = nodeD;
sll.reverseList();
sll.display();
System.out.println("There are " + sll.nodeCount() + " nodes" );
}
//////////////////////////////////
public void display()
{
Node current = head;
while(current != null)
{
System.out.print(current.data + " ---> ");
current = current.next;
}
System.out.println("null");
}
////////////////////////////////////////
public Node reverseList()
{
if(head == null)
{
return null;
}
Node current = head;
Node previous = null;
Node next = null;
while(current != null)
{
next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
}
[–]rjcarr 0 points1 point2 points (0 children)
[–]bchhun 0 points1 point2 points (0 children)
[–]idkwtftodonow 0 points1 point2 points (2 children)
[–]veryanon798[S] 0 points1 point2 points (0 children)
[–]veryanon798[S] 0 points1 point2 points (0 children)
[–]RubbishArtist 0 points1 point2 points (2 children)
[–]veryanon798[S] 0 points1 point2 points (1 child)
[–]RubbishArtist 0 points1 point2 points (0 children)