Write a generic method named genericListSort that takes a ge

Write a generic method named genericListSort that takes a generic linked list with elements of type E and rearranges the nodes so that the elements stored in the list are sorted into the order of smallest to largest. Use the comparable to decide if an element of the list is larger, smaller or equal to another element. To enable the use of comparable, your generic Node class must implement Java\'s Comparable interface.

The method listSort should be in a Java class called SortedGenericLinkedList as shown in the following.

public class SortedGenericLinkedList {

public <E> Node<E> genericListSort(Node<E> head) { /* your implementation */}

}

Solution

public class SortedGenericLinkedList<T> {

private static Node head;

private static Node tail;

public <T> Node<T> genericListSort(Node<T> head) {

Node<T> tmp = head;

while(true){

Node<T> tmp1 = tmp.getNextRef();

while(tmp1!=null){

if(tmp.getValue()>tmp1.getValue()){

int temp=tmp.getValue();

tmp.getValue()=tmp1.getValue();

tmp1.getValue()=temp;

}

tmp1= tmp1.getNextRef();

}

tmp = tmp.getNextRef();

}

return head;

}

public void add(T element){

Node<T> nd = new Node<T>();

nd.setValue(element);

System.out.println(\"Adding: \"+element);

/**

* check if the list is empty

*/

if(head == null){

//since there is only one element, both head and

//tail points to the same object.

head = nd;

tail = nd;

} else {

//set current tail next link to new node

tail.setNextRef(nd);

//set tail as newly created node

tail = nd;

}

}

public void display(){

Node<T> tmp = head;

while(true){

if(tmp == null){

break;

}

System.out.println(tmp.getValue());

tmp = tmp.getNextRef();

}

}

public static void main(String a[]){

SortedGenericLinkedList<Integer> sl = new SortedGenericLinkedList<Integer>();

sl.add(32);

sl.add(3);

sl.add(54);

sl.add(89);

sl.display();

sl.genericListSort(head);

sl.display();

}

}

Write a generic method named genericListSort that takes a generic linked list with elements of type E and rearranges the nodes so that the elements stored in th
Write a generic method named genericListSort that takes a generic linked list with elements of type E and rearranges the nodes so that the elements stored in th
Write a generic method named genericListSort that takes a generic linked list with elements of type E and rearranges the nodes so that the elements stored in th

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site