我试图在Java上进行插入排序。 '公共类节点 { 私有对象数据; 私有节点链接;
public Node(Object dataToAdd) {
data = dataToAdd;
link = null;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
}
And here is my Single Linked List Class
公共类 SingleLinkedList { 节点头;
public void insert(Object dataToAdd) {
Node newnode = new Node(dataToAdd);
if (head == null) {
head = newnode;
} else {
Node temp = head;
Object[] data = ((String) dataToAdd).split(";");
Object[] compare = ((String) temp.getData()).split(";");
System.out.println(data[1]);
if (Integer.valueOf((String) data[1]) < Integer.valueOf((String) compare[1])) {
temp = head;
head = newnode;
newnode.setLink(temp);
} else {
temp = head;
while (temp.getLink() != null)
temp = temp.getLink();
newnode.setLink(temp.getLink());
temp.setLink(newnode);
}
}
}
public void display() {
if (head == null) {
System.out.print(" ");
} else {
Node temp = head;
while (temp != null) {
System.out.print(temp.getData() + " ");
temp = temp.getLink();
}
}
}
public boolean previousCheck(char answer) {
int count = 1;
if (head == null) {
System.out.print(" ");
} else {
Node temp = head;
while (temp != null) {
if (answer == (char) temp.getData()) {
count++;
}
temp = temp.getLink();
}
if (count > 2) {
return true;
}
}
return false;
}
public Object get(int number) {
if (head == null) {
System.out.println("Linked is empty ");
return null;
} else {
Node temp = head;
while (temp != null) {
for (int i = 0; i < number; i++) {
temp = temp.getLink();
}
return temp.getData();
}
}
return null;
}
@Override
public String toString() {
return "SingleLinkedList [head=" + head + "]";
}
} `
我需要一种新的插入方法来执行插入排序。 读取了一个文件,输入的内容类似于名称;得分 我的目的是按分数对这些值进行排序。 一切似乎都很好。 然而,输出是这样发生的。 欧洲经委会;5 卡恩;15 佩林;30 阿里;50 耶利兹;25 杰姆;40罐;35 西贝尔;30 雷姆齐;20 纳赞;10
我对插入方法进行了一些修改,如下所示
public void insert(Object dataToAdd) {
Node newNode = new Node(dataToAdd);
if (head == null) {
head = newNode;
} else {
int score = getScore(dataToAdd);
int headObjectScore = getScore(head.getData());
if (score > headObjectScore) {
Node temp = head;
head = newNode;
newNode.setLink(temp);
} else {
Node currentNode = head;
//to handel if the newNode has the biggest score
if(currentNode.getLink()==null){
currentNode.setLink(newNode);
currentNode = newNode;
}
while (currentNode.getLink() != null){
Node oldNode = currentNode;
currentNode = currentNode.getLink();
if(score>getScore(currentNode.getData())){
oldNode.setLink(newNode);
newNode.setLink(currentNode);
break;
}
//to handel if the newNode has the biggest score
if(currentNode.getLink()==null){
currentNode.setLink(newNode);
currentNode = newNode;
}
}
}
}
}
private int getScore(Object data){
return Integer.valueOf(((String) data).split(";")[1]);
}