I have an issue in sorting a linked list. When I use this code the compiler enter an infinite loop and don't do any thing I've been asked to change an insert code to sort code
public void insert(int val) {
Node currentNode = head;
Node nextNode = head.next;
if (currentNode.num > val) {
Node tmpNode = head;
head = new Node(val);
head.next = tmpNode;
return;
}
if (nextNode != null && nextNode.num > val) {
currentNode.next = new Node(val);
currentNode.next.next = nextNode;
return;
}
while (nextNode != null && nextNode.num < val) {
currentNode = nextNode;
nextNode = nextNode.next;
}
currentNode.next = new Node(val);
currentNode.next.next = nextNode;
}
But that's what I come with it's looks so bad.
This must sort the linked list ... I think !?
public void sort() {
Node currentNode = head;
Node nextNode = head.next;
while (nextNode != null) {
if (currentNode.num > currentNode.next.num) {
Node tmpNode = currentNode;
currentNode.num = currentNode.next.num;
currentNode.next.num = tmpNode.num;
}
}
}