data structures - Inserting into Sorted LinkedList Java -
i have code below inserting new integer sorted linkedlist of ints not think "correct" way of doing things know there singly linkedlist pointer next value , doubly linkedlist pointers next , previous value. tried use nodes implement below case java importing import org.w3c.dom.node (document object model) got stuck.
insertion cases
- insert empty array
- if value inserted less everything, insert in beginning.
- if value inserted greater everything, insert in last.
could in between if value less than/greater values in ll.
import java.util.*; public class mainlinkedlist { public static void main(string[] args) { linkedlist<integer> llist = new linkedlist<integer>(); llist.add(10); llist.add(30); llist.add(50); llist.add(60); llist.add(90); llist.add(1000); system.out.println("old linkedlist " + llist); //what if want insert 70 in sorted linkedlist linkedlist<integer> newllist = insertsortedll(llist, 70); system.out.println("new linkedlist " + newllist); } public static linkedlist<integer> insertsortedll(linkedlist<integer> llist, int value){ llist.add(value); collections.sort(llist); return llist; }
}
this might serve purpose perfectly:
use code:
import java.util.*; public class mainlinkedlist { private static linkedlist<integer> llist; public static void main(string[] args) { llist = new linkedlist<integer>(); addvalue(60); addvalue(30); addvalue(10); addvalue(-5); addvalue(1000); addvalue(50); addvalue(60); addvalue(90); addvalue(1000); addvalue(0); addvalue(100); addvalue(-1000); system.out.println("linked list is: " + llist); } private static void addvalue(int val) { if (llist.size() == 0) { llist.add(val); } else if (llist.get(0) > val) { llist.add(0, val); } else if (llist.get(llist.size() - 1) < val) { llist.add(llist.size(), val); } else { int = 0; while (llist.get(i) < val) { i++; } llist.add(i, val); } } }
this 1 method manage insertion in list in sorted manner without using collections.sort(list)
Comments
Post a Comment