How to sort a linked list in java without using collections?
There are many ways to sort a linked list in java. Here We will see how to sort int linked list without using the collection.
package com.javacodestuffs.core.collection.linkedlist;
public class MyLinkedList {
private Node head;
MyLinkedList() {
head = null;
}
// Class for nodes
static class Node {
//data
int i;
Node next;
Node(int i) {
this.i = i;
this.next = null;
}
public void displayData() {
System.out.print(i + " ");
}
}
public void insertNode(int data) {
Node newNode = new Node(data);
Node current = head;
Node previous = null;
while (current != null && data > current.i) {
previous = current;
current = current.next;
}
// insertion at beginning of the list
if (previous == null) {
head = newNode;
} else {
previous.next = newNode;
}
newNode.next = current;
}
public Node removeNode() {
if (head == null) {
throw new RuntimeException("List is empty");
}
Node temp = head;
head = head.next;
return temp;
}
// Method to traverse and display all nodes
public void displayLinkedList() {
Node current = head;
while (current != null) {
current.displayData();
current = current.next;
}
System.out.println("");
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.insertNode(11);
list.insertNode(21);
list.insertNode(31);
System.out.println("After initial insertions : ");
list.displayLinkedList();
System.out.println();
list.insertNode(19);
list.insertNode(17);
list.insertNode(20);
list.insertNode(50);
System.out.println("After insertions Nodes : ");
list.displayLinkedList();
System.out.println();
Node node = list.removeNode();
System.out.println("Node removed : " + node.i);
list.displayLinkedList();
}
}
output:
After initial insertions :
11 21 31
After insertions Nodes :
11 17 19 20 21 31 50
Node removed : 11
17 19 20 21 31 50
Question/Articles related Sort the linked list in Java
How to Sort the linked list in Java
How to create a linked list in java?
How to print a linked list in java?
How to move a node in linked list java?
How to find middle element of linked list in java?
How to compare two linked lists in java?
How to delete a node in the linked list in java?
How to merge two linked list in java?
How to traverse a linked list java?
How to sort a linked list in java?
In this article, we have seen How to sort a linked list in java without using collections with examples. All source code in the article can be found in the GitHub repository.
0 Comments
Post a Comment