Home » Java » Java single list sorting method

Java single list sorting method

import java.util.Scanner;
/ * *
* JAVA uses the linked list to achieve the bubble sort
* @author mengfeiyang
*
* /
Public, class, ListSort {
Public, static, void, main (String[], args) {
ListClass list = new, ListClass ();
Scanner scan = new Scanner (System.in);
Int, I, size;
System.out.print (enter the size of the list:);
Size = scan.nextInt ();
For (i=0; iList.addAt (I, scan.nextInt ());
}
System.out.println (list of nodes: ");
List.listAll ();
List.bubbleSort ();
System.out.println (sorted list of nodes: ");
List.listAll ();
}
}
/ * *
* list class
* /
Class NodeClass{
Private int data;
Private NodeClass next; / / pointer domain node list, point to a direct successor node
Public, NodeClass () {
Next = null;
}
Public NodeClass (int, data, NodeClass, next) {
This.data = data;
This.next = next;
}
Public, int, getData () {
Return this.data;
}
Public, void, setData (int, data) {
This.data = data;
}
Public, NodeClass, getNext () {
Return this.next;
}
Public, void, setNext (NodeClass, next) {
This.next = next;
}
}
/ * *
* list class
* /
Class ListClass{
Private NodeClass head = null; / / pointer head
Private int size = 0;
Public, ListClass () {
Head = new, NodeClass ();
Size = 0;
}
Insert the elements in the I position / / elem
Public, Boolean, addAt (int, I, int, elem) {
If (I < 0 > size {I ||)
Return false;
}
NodeClass, pre, curr;
Int pos;
For (pre=head; i>0) and pre.getNext (=null; i--, pre=pre.getNext (!));
Curr = new, NodeClass (elem, pre.getNext ());
Pre.setNext (curr);
Size++;
Return true;
}
Public, NodeClass, getHead () {
Return this.head;
}
Public, void, setHead (NodeClass, head) {
This.head = head;
}
Public, int, getSize () {
Return this.size;
}
Public, Boolean, isEmpty () {
Return (size==0);
}
Public, void, listAll () {
For (NodeClass, curr=head.getNext (), curr, =null, curr=curr.getNext ()) {
System.out.print (curr.getData () + "t");
}
System.out.println ();
}
Public, void, bubbleSort () {
NodeClass, P, q;
Int temp;
For (p=head.getNext (); p.getNext (); =null; p=p.getNext ()) {
For (q=head.getNext (); q.getNext (); =null; q=q.getNext ()) {
If (q.getData () > q.getNext ().GetData ()) {
Temp = q.getData ();
Q.setData (q.getNext ().GetData ());
Q.getNext ().SetData (temp);
}
}
}
}
}

Latest