while(the first list still has nodes)
{
1. Find the node with the largest element
2. Remove this node from the first list
3. Add this node at the head of the second list
}
I think i have everything in place but when I execute the while loop it ends up being an infinite loop and I cannot figure out why. Here is my code so far:
public class Project3
{
public static void main (String Args[])
{
//Declarations
IntNode head = null;
IntNode cursor;
IntNode sorted;
int maxValue = 0;
//Creates the linked list of integers
head = new IntNode(3, null);
head = new IntNode(98, head);
head = new IntNode(105, head);
head = new IntNode(85, head);
//Display the length of the list
System.out.println("List Length: " + IntNode.listLength(head));
//display the linked list
for (cursor = head; cursor != null; cursor = cursor.getLink())
{
int count = 1;
System.out.println(count + ": " + cursor.getData());
count++;
}
//Testing of the max value
System.out.println("the final max value is: " + findMax(head));
//Initiate the sorting method
System.out.println("The sorted list.");
sorted = listSort(head);
for (cursor = sorted; cursor != null; cursor = cursor.getLink())
{
int count = 1;
System.out.println(count + ": " + cursor.getData());
count++;
}
}
private static int findMax(IntNode head)
{
int maxValue = 0;//default number to compare to
//for loop to traverse the linked list
for (IntNode cursor = head; cursor.getLink()!= null; cursor = cursor.getLink())
{
if (cursor.getData() > maxValue)//if the specific element is greater than 0 or a max value already set...
{
maxValue = cursor.getData();//It will change the max value to the element
}
}
return maxValue;//Returns the max value as an int to be used to sort the linked list
}
private static IntNode listSort(IntNode head)
{
IntNode sorted = new IntNode(findMax(head), null);
while(head.getLink() != null)//the first list has nodes
{
//1. Find the node with the largest element
if (head.getData() <= findMax(head))
{
sorted = new IntNode(findMax(head), sorted);//Add it to the new list
head.removeNodeAfter();//remove it from the original
head = head.getLink();
}
else
{
System.out.println("Empty.");
}
findMax(head);
}
return sorted;
}
}

New Topic/Question
Reply
MultiQuote












|