Java 如何在已排序的链表中插入数字

Java 如何在已排序的链表中插入数字,java,linked-list,Java,Linked List,我有一个作业,我需要写一个叫做IntListTwo的类,它代表一个双向链表。 我有一个给定的类,叫做IntNodeTwo public class IntNodeTwo { private int _num; private IntNodeTwo _next, _prev; public IntNodeTwo(int n) { _num = n; _next = null; _prev = null; } public IntNodeTwo(int num, IntNodeTwo

我有一个作业,我需要写一个叫做IntListTwo的类,它代表一个双向链表。 我有一个给定的类,叫做IntNodeTwo

public class IntNodeTwo
{
 private int _num;
 private IntNodeTwo _next, _prev;
 public IntNodeTwo(int n) {
 _num = n;
 _next = null;
 _prev = null;
 }
 public IntNodeTwo(int num, IntNodeTwo n, IntNodeTwo p) {
 _num = num;
 _next = n;
 _prev = p;
 }
 public int getNum() { return _num; }
 public IntNodeTwo getNext() { return _next; }
 public IntNodeTwo getPrev() { return _prev; }
 public void setNum (int n) { _num = n; }
 public void setNext (IntNodeTwo node) { _next = node; }
 public void setPrev (IntNodeTwo node) { _prev = node; }
} 

在INTLISTwo中,我有一个字段\u head,它是列表的头

这就是我想做的

public void addNumber(int num) {

        IntNodeTwo p = new IntNodeTwo(num);

        if (_head == null) {
            _head.setNum(num);
            return;
        }
        if (_head.getNum() > num) {
            IntNodeTwo temp = _head;
            _head = _head.getNext();
            temp = p;
            return;
        }
        else {
            _head = _head.getNext();
            addNumber(num);

        }
    }
例如,如果我有一个列表{2,5,8,9},num是4,我会得到{2,4,5,8,9}

有一些很好的技巧来调试代码,找出哪里出了问题。以下是我注意到的几件事:

if (_head == null) {
            _head.setNum(num);
            return;
        }
因为这里的_head为null,_head.setNumnum;将引发异常。您需要将其指向一个新节点,而不是:

_head = p;

每次更改列表的标题时:

_head = _head.getNext();
这似乎是个问题。当您的方法完成时,您如何知道列表的原始标题?相反,您应该使用一个临时节点变量,可能名为_curr或类似的名称

我认为在解决这些问题后,递归解决方案应该会起作用。您可能还希望研究一个迭代解决方案,而不是使用while循环

如果这仍然不起作用,请务必阅读我上面链接的文章。学习如何调试代码是一项重要的技能

    public void addNumber(int num) {

    IntNodeTwo p = new IntNodeTwo(num);

    if (_head == null) {
        _head = new IntNodeTwo(num);
        _head = _tail;
        return;
    }
    if (_head.getNum() > num) {
        IntNodeTwo temp = new IntNodeTwo(num,_head,null);
        temp = _head;

        return;
    }
    else {
        while(num > _head.getNum()) {
            if(_head == null) {
                _head = new IntNodeTwo(num);
                break;
            }
            else {
                p = _head.getNext();
                p = new IntNodeTwo(num);
            }
        }

    }
}

这就是我现在拥有的。仍然不起作用。

我建议在这里使用循环而不是递归。您还应该使用中的提示逐步查找代码中的任何问题,并了解到目前为止您编写的内容。但是如何使用for循环,我不知道列表的长度抱歉,我说错了。while循环比for循环更合适。我编辑了我以前的评论。我解决了第一个问题,知道何时打印列表。我刚得到我加的最后一个号码。每次添加新的时,我都会覆盖上一个one@YftachSrur您还需要将p.next设置为指向右侧节点。