1

这个问题要我为我的 LList 类编写一个方法,假设列表已经按排序顺序,它将在正确的位置添加一个新节点。我正在处理的列表是一个队列。

这是我的 LNode 类:

class LNode{
    private int val;
    private LNode next;
    private LNode prev;
    public LNode(int v, LNode n, LNode p){
        next = n;
        prev = p;
        val = v;
    }
    public int getVal(){
        return val;
    }
    public LNode getNext(){
        return next;
    }
    public LNode getPrev(){
        return prev;
    }
    public void setVal(int v){
        val = v;
    }
    public void setNext(LNode n){
        next = n;
    }
    public void setPrev(LNode p){
        prev = p;
    }
}

这是我的 LTest 课程:

public class LTest{
    public static void main(String[]args){
        LList nums = new LList();
        nums.enqueue(55);
        nums.enqueue(20);
        nums.enqueue(13);
        nums.enqueue(11);
        nums.sortedInsert(15);


        nums.display();
    }
}

这是我在 LList 类中尝试过的:

public void sortedInsert(int v){
    LNode tmp = head;
    while(v<tmp.getVal()){
        tmp = tmp.getNext();
    }
    tmp.setNext(tmp.getPrev().getNext());//tmp's next is now the original LNode
    tmp.getPrev().getNext().setPrev(tmp);//the original LNode's previous is now tmp
    tmp.getPrev().setNext(tmp);//tmp's previous LNode's next is now tmp
    tmp.setVal(v);
}

它不起作用,输出是 55,20,然后是 15 永远和 java 崩溃。我猜这是因为 tmp LNode 指向它自己,但对我来说,我的代码并没有这样做。那么谁能告诉我怎么了?谢谢你。

4

1 回答 1

2

From my first look at your code it looks as though you do not actually create a new node for the new value v in the sortedInsert method. I think you will need to create a new node then itereate through your LinkedList then attach the new node and not really worry about setting the value of the data because it will be captured in the new node. Kind of something like this maybe...

LNode newnode = new LNode();
newnode.setVal(v);

LNode tmp = head;

while(v < head.getVal())
{
   //etc...
}

Don't forget that if the new node is at the beginning you need to change your head variable to point to the newnode.

于 2013-03-07T02:58:01.233 回答