【发布时间】:2018-04-24 15:28:38
【问题描述】:
我有一个要排序的节点列表。
节点:
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;
}
}
列表:
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;
}
}
主要:
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 天。我已经尝试了其他示例以及所有这些,但我无法深入了解它。对这些数字进行排序的最简单方法是什么?
【问题讨论】:
-
不清楚你在问什么;
sort怎么写?这不是重点吗?弄明白?有各种各样的参考资料和教程讨论这个主题。 -
我想我一直在尝试插入排序。
-
Bubble sort 是一种相对简单的排序算法,在链表上实现起来很简单。
-
尝试编写一些排序代码并用它发回,而不是要求 SO 为你做。
标签: java linked-list singly-linked-list