I'm working on a program where I have an issue sorting my list. (I just started with Linked List)
Can you help me with how to sort the list from the code I just wrote? Or suggest me a code for it?
Here is my code :
//124. I. Write a Java program to find the index of a value in a sorted array. II.If the value does not find return the index where it would be if it were inserted in order. // My approach is to convert the array to a list. For case II, I planned to add the value to the list, sort it and then get the index. import java.util.*; public class indexSortedArray { public static void main(String[] args) { Integer[] nums = { 1, 2, 4, 5, 6 }; List<Integer> list = Arrays.asList(nums); java.util.LinkedList<Integer> linkedList = new java.util.LinkedList<Integer>(list); linkedList.add(0); System.out.println("LinkedList of above array : " + linkedList); // int getIndex = Arrays.asList(nums).indexOf(0); // System.out.println("0 is located at " + getIndex + " index"); // if (getIndex == -1) { // Arrays.asList(nums).add(0); // } } }
I tried several approaches but it didn't work. My last approach was with the following piece of code I added but didn't do work so I removed it.
public Node head = null; public void sortList() { // Node current will point to head Node current = head, index = null; int temp; if (head == null) { return; } else { while (current != null) { // Node index will point to node next to // current index = current.next; while (index != null) { // If current node's data is greater // than index's node data, swap the data // between them if (current.data > index.data) { temp = current.data; current.data = index.data; index.data = temp; } index = index.next; } current = current.next; } } }