问题描述
我在下面有这个代码,我将一个新整数插入到一个有序的整数链表中,但我认为这不是正确"的做事方式,因为我知道有指向下一个值的指针的单链表和带有指向下一个和上一个值的指针的双链表.我尝试使用 Nodes 来实现以下案例,但 Java 正在导入此 import org.w3c.dom.Node(文档对象模型),因此卡住了.
I have this code below where I am inserting a new integer into a sorted LinkedList of ints but I do not think it is the "correct" way of doing things as I know there are singly linkedlist with pointer to the next value and doubly linkedlist with pointers to the next and previous value. I tried to use Nodes to implement the below case but Java is importing this import org.w3c.dom.Node (document object model) so got stuck.
插入案例
- 插入空数组
- 如果要插入的值小于所有值,则在开头插入.
- 如果要插入的值大于所有值,则插入最后一个.
如果值小于/大于 LL 中的某些值,则可能介于两者之间.
- Insert into Empty Array
- If value to be inserted less than everything, insert in the beginning.
- If value to be inserted greater than everything, insert in the last.
Could be in between if value less than/greater than certain values in LL.
import java.util.*;
public class MainLinkedList {
public static void main(String[] args) {
LinkedList<Integer> llist = new LinkedList<Integer>();
llist.add(10);
llist.add(30);
llist.add(50);
llist.add(60);
llist.add(90);
llist.add(1000);
System.out.println("Old LinkedList " + llist);
//WHat if you want to insert 70 in a sorted LinkedList
LinkedList<Integer> newllist = insertSortedLL(llist, 70);
System.out.println("New LinkedList " + newllist);
}
public static LinkedList<Integer> insertSortedLL(LinkedList<Integer> llist, int value){
llist.add(value);
Collections.sort(llist);
return llist;
}
}
推荐答案
这可能完全符合您的目的:
This might serve your purpose perfectly:
使用此代码:
import java.util.*;
public class MainLinkedList {
private static LinkedList<Integer> llist;
public static void main(String[] args) {
llist = new LinkedList<Integer>();
addValue(60);
addValue(30);
addValue(10);
addValue(-5);
addValue(1000);
addValue(50);
addValue(60);
addValue(90);
addValue(1000);
addValue(0);
addValue(100);
addValue(-1000);
System.out.println("Linked List is: " + llist);
}
private static void addValue(int val) {
if (llist.size() == 0) {
llist.add(val);
} else if (llist.get(0) > val) {
llist.add(0, val);
} else if (llist.get(llist.size() - 1) < val) {
llist.add(llist.size(), val);
} else {
int i = 0;
while (llist.get(i) < val) {
i++;
}
llist.add(i, val);
}
}
}
这种方法将在不使用 Collections.sort(list)
这篇关于插入排序的 LinkedList Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!