【问题标题】:Adding in a Sorted Linked List添加排序链表
【发布时间】:2018-03-29 22:21:02
【问题描述】:

所以我正在为存储整数的 Sorted LinkedList 编写代码。整数相加时必须按升序存储。我的 Node 类代码有两个值和构造函数,这里没有写,因为它们很明显。

public class Node {
int value;
Node next;
}

我的排序链接列表的部分代码是

public class SortedList {

Node head;
public int listCount;


public SortedList(){
    listCount = 0;
    this.head=null;

}



public void add(int num){
    Node newNode= new Node(num);
    Node temp=head;

    if (head==null) {
        head=newNode;
        listCount++;
        System.out.println("Node with data "+num+" was added.");
    }
     else {
        while ((temp.value < num) && (temp.next!=null)) {
            temp = temp.next;
        }
        if (temp.next==null){
            temp.next=newNode;
            listCount++;
            System.out.println("Node with data "+num+" was added.");
        }
        else {
            newNode.next=temp.next.next;
            temp.next=newNode;
            listCount++;
            System.out.println("Node with data "+num+" was added.");
        }


    }

}

所以当我测试我的代码并添加数字 1、81、63、7、8、9、23 时,我的输出是

添加了数据为 1 的节点。添加了数据为 81 的节点。 添加了数据为 63 的节点。 添加了数据为 7 的节点。 添加了数据为 8 的节点。 添加了数据为 9 的节点。 添加了数据为 23 的节点。 1 -> 81 -> 23 END 列表计数为 7

所以你可以看到,当我尝试显示链表时,只有 1 指向 81,指向 23。所有其他值都丢失了。 我使用此代码获取输出:

      public String toString(){
        Node temp = head;
        while(temp.next!=null){
            System.out.print(temp.value+" -> ");
            temp = temp.next;
        }
        System.out.print(temp.value);
        return " END List Count is "+listCount;

}

【问题讨论】:

    标签: java linked-list singly-linked-list


    【解决方案1】:

    你在这行写错了:

    newNode.next=temp.next.next;
    

    请改成:

    newNode.next=temp.next;
    

    【讨论】:

      【解决方案2】:

      您的实施中有两个问题。第一个是导致价值丢失。这个问题出在作业上——

      newNode.next=temp.next.next;
      

      改成-

      newNode.next=temp.next;
      

      第二个是你的while条件检查-

      (temp.value < num) && (temp.next!=null)
      

      这将破坏排序顺序。将其更改为 -

      (temp.next!=null) && (temp.next.value < num)
      

      【讨论】:

      • 谢谢,当我将 while 循环更改为此时,我得到 NullPointerexeption
      猜你喜欢
      • 1970-01-01
      • 2011-06-17
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多