给定一个LinkedList,保证每次往里添加元素的时候,链表仍然有序
LinkedList这个集合之前挺少用的,所以里面的方法都不怎么记得,导致做题的时候思路乱了。
过后看了LinkedList的api,写出了双指针的解法。前后花费1h。
import java.util.*;
public class LinkedListTest {
static LinkedList<Integer> list = new LinkedList<>();
//一根指针,做题时想实现的方法
public static void addElement1(int n) {
int index = 0;
for (Integer i : list) {
if (i < n) {
index++;
continue;
}
}
list.add(index, n);
}
//两根指针
public static void addElement2(int n) {
int right = list.size() - 1;
int left = 0;
//避免重复加入
boolean add = false;