У меня есть список узлов, которые я хотел бы отсортировать.
Node:
package lab.pkg14;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
public void display() {
System.out.println(this.data);
}
@Override
public String toString() {
String out = "";
return out + data;
}
}
List:
class LinkedList {
private Node head; //First item in LL
private int length; //Number of items.
boolean isEmpty;
public LinkedList() {
this.length = 0;
isEmpty = true;
}
public int getLength() { //Getter, NO setter
return length;
}
public void add(int item) { //Adds node at the front.
Node myNode = new Node(item);
myNode.next = this.head;
this.head = myNode;
this.length++;
isEmpty = false;
}
public int peek() { //Returns value at head of list. Doesn't alter the list.
return head.data;
}
public boolean find(int item) { //Looks through the list for the int.
boolean foundit = false; //You'll want to use .equals() if its generic. //code
return foundit;
}
public void displayList() {
Node runner = head;
while (runner != null) {
runner.display();
runner = runner.next;
}
}
public int addList() {
Node runner = head;
int sum = 0;
while (runner != null) {
sum += runner.data;
runner = runner.next;
}
return sum;
}
public Node remove() { //Removes the head.
Node headData = head;
if (!isEmpty) {
this.head = head.next;
}
return headData;
}
public boolean remove(int item) { //Removes first instance of the specified item.
boolean foundData = false;
Node current = head;
Node previous = head;
if (!isEmpty) {
while (current.data != item) {
if (current.next == null) {
foundData = false;
} else {
previous = current;
current = current.next;
}
}
if (current == head) {
head = head.next;
foundData = true;
} else {
previous.next = current.next;
foundData = true;
}
}
return foundData;
} //Returns true if it found it and removed it.
public void sort() { //Obvious, right?
}
@Override
public String toString() { //Makes debugging easier.
String out = "";
Node current = head;
for (int i = 1; i <= this.length; i++) {
out = out + current.data + " ";
current = current.next;
}
return out;
}
}
Main:
public class Lab14 {
public static void main(String[] args) {
LinkedList myll = new LinkedList();
myll.add(15);
myll.add(16);
myll.add(17);
myll.add(18);
myll.add(19);
System.out.println("Length: ");
System.out.println(myll.getLength());
System.out.println("Head: ");
System.out.println(myll.peek());
System.out.println("Full list: ");
myll.displayList();
System.out.println("Sum: ");
System.out.println(myll.addList());
System.out.println(myll.remove());
System.out.println(myll.remove(17));
System.out.println("Full list with 19 and 17 removed: ");
myll.displayList();
}
}
Я пытаюсь научиться самостоятельно писать код и просто не могу этого понять. Я пытался отсортировать эти цифры более 3 дней. Я пробовал другие примеры и все такое, но я просто не могу докопаться до сути. Какой самый простой способ сортировки этих чисел?