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

时间:2019-06-06 19:45:08

标签: 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 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; }
} 

在IntListTwo中,我有一个字段“ _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}

2 个答案:

答案 0 :(得分:0)

This article提供了一些调试技巧,可以帮助您调试代码以查找问题所在。这是我注意到的几件事:

if (_head == null) {
            _head.setNum(num);
            return;
        }

由于_head在此处为null,因此_head.setNum(num);将引发异常。您需要将其指向一个新节点,而不是:

_head = p;

您每次都更改列表的标题:

_head = _head.getNext();

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

我认为您的递归解决方案应在解决这些问题后起作用。您可能还想研究带while循环的迭代解决方案。

如果仍然无法解决问题,请务必阅读我上面链接的文章。学习如何调试代码是一项重要技能。

答案 1 :(得分:0)

    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);
            }
        }

    }
}

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