Make a Linked list to Enter numbers and sort them.
import java.util.*;
class Node {
protected int data = 0;
protected Node link = null;
public Node() {
}
public Node(int d, Node next) {
data = d;
link = next;
}
public void setLink(Node n) {
link = n;
}
public void setData(int d) {
data = d;
}
public int getDeta() {
return data;
}
public Node getLink() {
return link;
}
}
class linkedList {
protected Node start = null;
public boolean isEmpty() {
return start == null;
}
public void insert(int val) {
Node nptr = new Node(val, null);
if (isEmpty()) {
start = nptr;
} else if (val <= start.getDeta()) {
nptr.setLink(start);
start = nptr;
} else {
Node ptr = start.getLink(), save;
save = start;
while (ptr != null) {
if (val >= save.getDeta() && val <= ptr.getDeta()) {
save.setLink(nptr);
nptr.setLink((ptr));
return;
} else {
save = ptr;
ptr = ptr.getLink();
}
}
save.setLink(nptr);
}
}
public void show() {
System.out.println("Sorted LinkedList");
Node ptr = start;
for (; ptr.getLink() != null; ptr = ptr.getLink())
System.out.printf("%d --> ", ptr.getDeta());
System.out.printf("%d !!!!\n", ptr.getDeta());
}
}
public class LinkSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
linkedList list = new linkedList();
System.out.println("Enter Numbers to insert in list: ");
for (int x = 1; x <= 5; x++) {
int num = sc.nextInt();
list.insert(num);
System.out.printf("Inserted: %s\n", num);
}
list.show();
sc.close();
}
}
Name | Type | Uses |
---|---|---|
Class Node | ||
global | ||
data | int | value to be stored in the current node |
link | Node | pointer for the next node |
Class linkedList | ||
global | ||
start | Node | stores the pointer to starting node of the linked list |
public void insert() | ||
val | int | argument :- the value to be inserted in linked list |
nptr | Node | node made using the value 'val' to insert in the list |
ptr | Node | used as a temporary pointer to traverse the linked list |
save | Node | to store pointer of the previous Node |
public void show() | ||
ptr | Node | used as a temporary pointer to traverse the linked list |
Class LinkSort | ||
void main() | ||
sc | Scanner | object to take user input |
list | linkedList | object to store our linked auto-sorted linked list |
num | int | to store enetred number |