请帮助我插入方法。我想在双向链表中插入一个值大于该 int 的 int。然后新的 int 将替换双向链表中更大的值(我得到了很好的工作)。但现在我希望更大的 int 出现在列表中并在适当的地方插入。
如果我说 insert 2 4 6 8 ,它会起作用(结果:2 4 6 8)如果我然后插入 1(小于 2)
结果将是 1 4 6 8 2
问题是,当我插入让我们说 7(大于 6,但小于 8)时,我不知道如何向下行并在适当的地方插入。
enter code here
public void insert(int newInt) { Cell newCell = new Cell (newInt);
if (this.size() == 0){
smallest = newCell;
}
for (Cell i = smallest; i != null; i = i.right){
// if newCell is the larger than all in row, then add it to the end.
if (newCell.value > i.value && i.right == null){
i.right = newCell;
}
// if newCell is smaller than smallest, then add it to smallest and old smallest will go down the list (compare and put it where appropriate).
if (newCell.value < smallest.value){
newCell.below = smallest;
newCell.right = smallest.right;
smallest.right = null;
smallest = newCell;
}
// if newCell is smallest than any element, then replace that cell with newCell, and send that cell to below row
// do again untill all below rows are sorted. hence this could be a while loop.
if (newCell.value > i.value && newCell.value < i.right.value){
System.out.println("newCell is " + newCell);
Cell largerRight = i.right;
newCell.right = largerRight.right;
largerRight.right = null;
i.right = newCell;
temp = smallest.below;
while (temp != null){
System.out.println(temp);
for (Cell k = temp; k != null; k = k.right){
if (largerRight.value > temp.value && temp.right == null){
temp.right = largerRight;
temp = null;
}
}
temp =temp.below;
}
}
}
}//end insert