Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从零开始排序插入到单链表中_Java_Sorting_Singly Linked List - Fatal编程技术网

Java 从零开始排序插入到单链表中

Java 从零开始排序插入到单链表中,java,sorting,singly-linked-list,Java,Sorting,Singly Linked List,我一直在尝试从头开始创建一个排序链表,它只接受字符串,但在插入时对其进行排序。这是我目前的代码: import java.util.Arrays; public class SortedLinkedList { private StringNode head = null; /** * Default Constructor for a sorted linked list */ public SortedLinkedList() {}

我一直在尝试从头开始创建一个排序链表,它只接受字符串,但在插入时对其进行排序。这是我目前的代码:

import java.util.Arrays;

public class SortedLinkedList {

    private StringNode head = null;

    /**
     * Default Constructor for a sorted linked list
     */
    public SortedLinkedList() {}

    /**
     * Will add a new node with the specified data to the correctly sorted 
     * position in the list
     */
    public void add(String data) {

        if (head == null) {
            head = new StringNode(data);
        }

        StringNode temp = new StringNode(data);
        StringNode current = head;

        if (current != null) {
            while (current.getNext() != null) {
                if (current.getData().toString().compareTo(current.getNext().getData().toString()) < 0) {
                    temp.setNext(current.getNext());
                    current.setNext(temp);
                } else
                    current.setNext(temp);
            }
        }
    }

    /**
     * Will remove the node that matches the specified data from the list.
     * Returns true if node is found, otherwise will return false
     */
    public boolean remove(String data) {
        StringNode current = head;

        if (head != null) {

            while (current.getNext() != null) {

                if (current.getData().toString().equals(data)) {
                    current.setNext(current.getNext().getNext());
                    return true;
                }

                current = current.getNext();
            }
        }
        return false;
    }

    /**
     * Will cycle through the list and display each item on a new line
     */
    public void display() {

        if (head != null) {

            StringNode current = head.getNext();
            System.out.print("[");

            while (current.getNext() != null) {
                System.out.print(current.getData().toString() + ", ");
                current = current.getNext();
            }

            System.out.print("]");
        }
    }

    // Inner Class 

    class StringNode {

        String data;
        StringNode next;

        public StringNode(String nodeData) {
            next = null;
            data = nodeData;
        }

        /**
         * Getter of Data
         */
        public String getData() {
            return data;
        }

        /**
         * Getter of Next
         */
        public StringNode getNext() {
            return next;
        }

        /**
         * Setter of Data
         */
        public void setData(String newData) {
            data = newData;
        }

        /**
         * Setter of Next
         */
        public void setNext(StringNode nextNode) {
            next = nextNode;
        }
    }

}

是显示方法第70行中的空指针异常,这是while循环的创建。我完全迷路了,需要一些指导。谢谢。

由于最后一个元素的.getNext()为null,您实际上需要检查current==null

while (current != null)
稍微重构一下:

// should print [] for empty SLL; no dangling comma
public void display() {

  String out = "[";
  StringNode current = head;

  while(current != null) {
      out = out + current.getData();
      current = current.getNext();
      if (current != null)
        out = out + ", ";
  }
  out += "]";
  System.out.print(out);
}
编辑:此外,您的添加/删除方法需要重新修改。。。试着在纸上一步一步地检查算法,然后将条件/操作转换为Java

例如:

/**
 * Will add a new node with the specified data to the correctly sorted 
 * position in the list
 */
public void add(String data) {
  StringNode temp = new StringNode(data);

  if(head == null) {
      head = temp;
      return; // only adding one node
  }

  StringNode previous = head;

  if (data.compareTo(previous.getData()) < 0) {
     head = temp; // temp < head, so we add it to the beginning
     head.setNext(previous);
     return; // done
  }

  StringNode current = previous.getNext();

  while (current != null) {
      if (data.compareTo(current.getData()) < 0) {
          temp.setNext(current);
          previous.setNext(temp);
          return; // done
      } else {
          previous = current;
          current = previous.getNext();
      }
  }
  // current == null, so we reached the end of the list;
  previous.setNext(temp);
}
/**
*将使用指定的数据将新节点添加到正确排序的
*排名
*/
公共void添加(字符串数据){
StringNode temp=新StringNode(数据);
if(head==null){
压头=温度;
return;//仅添加一个节点
}
StringNode-previous=头部;
if(data.compareTo(previous.getData())<0){
head=temp;//temp
您实际上想要检查current==null,因为最后一个元素的.getNext()为null

while (current != null)
稍微重构一下:

// should print [] for empty SLL; no dangling comma
public void display() {

  String out = "[";
  StringNode current = head;

  while(current != null) {
      out = out + current.getData();
      current = current.getNext();
      if (current != null)
        out = out + ", ";
  }
  out += "]";
  System.out.print(out);
}
编辑:此外,您的添加/删除方法需要重新修改。。。试着在纸上一步一步地检查算法,然后将条件/操作转换为Java

例如:

/**
 * Will add a new node with the specified data to the correctly sorted 
 * position in the list
 */
public void add(String data) {
  StringNode temp = new StringNode(data);

  if(head == null) {
      head = temp;
      return; // only adding one node
  }

  StringNode previous = head;

  if (data.compareTo(previous.getData()) < 0) {
     head = temp; // temp < head, so we add it to the beginning
     head.setNext(previous);
     return; // done
  }

  StringNode current = previous.getNext();

  while (current != null) {
      if (data.compareTo(current.getData()) < 0) {
          temp.setNext(current);
          previous.setNext(temp);
          return; // done
      } else {
          previous = current;
          current = previous.getNext();
      }
  }
  // current == null, so we reached the end of the list;
  previous.setNext(temp);
}
/**
*将使用指定的数据将新节点添加到正确排序的
*排名
*/
公共void添加(字符串数据){
StringNode temp=新StringNode(数据);
if(head==null){
压头=温度;
return;//仅添加一个节点
}
StringNode-previous=头部;
if(data.compareTo(previous.getData())<0){
head=temp;//temp
我对您的代码进行了一些重构,并删除了您编写的代码注释。 相反,我添加了一些我自己的评论

请参阅这些注释,并考虑为编写的任何代码编写单元测试。它将帮助您捕获任何bug,并让您对正在发布的代码充满信心

package com.so36046948;

public class SortedLinkedList {

  private StringNode head = null;

  public SortedLinkedList() {}

  public void add(String data) {
    // Do null checks on Data.
    if (head == null) {
      // If we have no head, set head and return immediately.
      head = new StringNode(data, null);
      return;
    }

    StringNode previous = head;
    StringNode current = head;
    StringNode temp = new StringNode(data);

    // Continue iterating till we reach the end of the list.
    while (null != current) {

      if (current.getData().compareTo(data) < 0) {
        if (current == head) {
          // Special handling for the case when the element being inserted is greater than head.
          head = temp;
          temp.setNext(current);
          return;
        }
        break;
      }
      previous = current;
      current = current.getNext();
    }

    // Break out of the while loop and reset the next pointers. Previous points to immediate 
    // greater element and current points to immediate element that is less than *data* being
    // inserted.
    previous.setNext(temp);
    temp.setNext(current);
  }

  public void display() {
    // Consider overriding toString method instead of creating a display method,
    if (null == head) {
      System.out.println("List is empty.");
      return;
    }

    StringBuilder sb = new StringBuilder();
    StringNode current = head;
    sb.append("[");
    while (current != null) {
      sb.append(current.getData()).append(",");
      current = current.getNext();
    }
    sb.append("]");
    System.out.println(sb);
  }

  // Inner Class

  class StringNode {

    private final String data;
    private StringNode next;

    public StringNode(String nodeData) {
      next = null;
      data = nodeData;
    }

    public StringNode(String nodeData, StringNode next) {
      this.next = next;
      data = nodeData;
    }

    /**
     * Getter of Data
     */
    public String getData() {
      return data;
    }

    /**
     * Getter of Next
     */
    public StringNode getNext() {
      return next;
    }

    /**
     * Setter of Next
     */
    public void setNext(StringNode nextNode) {
      next = nextNode;
    }
  }

  public static void main(String[] args) {
    // Consider writing unit tests. I have created skeletons of a few rudimentry tests,
    // you may add more.
    test_insertInDscendingOrder();
    test_insertInAscendingOrder();
    test_insertTwoElements();
    test_insertSingleElement();
    //test_insertNullData();
  }

  private static void test_insertInDscendingOrder() {
    SortedLinkedList name = new SortedLinkedList();
    name.add("v");name.add("b");name.add("a");name.display();
  }

  private static void test_insertInAscendingOrder() {
    SortedLinkedList name = new SortedLinkedList();
    name.add("a");name.add("b");name.add("c");name.add("d");
    name.display();
  }

  private static void test_insertTwoElements() {
    SortedLinkedList name = new SortedLinkedList();
    name.add("a");name.add("b");name.display();
  }

  private static void test_insertSingleElement() {
    SortedLinkedList name = new SortedLinkedList();
    name.add("a");name.display();
  }

  private static void test_insertNullData() {
    // This would fail, Consider handling null data.
    SortedLinkedList name = new SortedLinkedList();
    name.add("a");
    name.add(null);
    name.display();
  }
}
package com.so36046948;
公共类分类链接列表{
私有StringNode头=null;
公共分类链接列表(){}
公共void添加(字符串数据){
//对数据执行空检查。
if(head==null){
//如果我们没有头颅,那就定下头颅,马上回来。
head=新的StringNode(数据,null);
返回;
}
StringNode-previous=头部;
StringNode电流=磁头;
StringNode temp=新StringNode(数据);
//继续迭代,直到到达列表的末尾。
while(null!=当前){
if(current.getData().compareTo(data)<0){
如果(当前==水头){
//插入的元件大于头部时的特殊处理。
压头=温度;
温度设置下一步(当前);
返回;
}
打破
}
先前=当前;
current=current.getNext();
}
//中断while循环并重置下一个指针。将上一个指针重置为立即指针
//较大元素和当前元素指向小于*数据*的立即元素
//插入。
上一个。设置下一个(临时);
温度设置下一步(当前);
}
公共空间显示(){
/考虑重写ToStin方法,而不是创建显示方法,
if(null==头){
System.out.println(“列表为空”);
返回;
}
StringBuilder sb=新的StringBuilder();
StringNode电流=磁头;
某人加上(“[”);
while(当前!=null){
sb.append(current.getData()).append(“,”);
current=current.getNext();
}
某人加上(“]”);
系统输出打印LN(sb);
}
//内部阶级
类StringNode{
私有最终字符串数据;
私有节点下一步;
公共StringNode(字符串节点数据){
next=null;
数据=节点数据;
}
公共StringNode(字符串节点数据,StringNode下一个){
this.next=next;
数据=节点数据;
}
/**
*数据获取者
*/
公共字符串getData(){
返回数据;
}
/**
*下一代的获得者
*/
公共StringNode getNext(){
下一步返回;
}
/**
*下一步的制定者
*/
公共void setNext(StringNode nextNode){
next=nextNode;
}
}
公共静态void main(字符串[]args){
/考虑编写单元测试。我已经创建了几个基本入门测试的骨架,
//你可以再加一点。
测试_insertInDscendingOrder();
测试_insertInAscendingOrder();
test_inserttwonents();
test_insertSingleElement();
//test_insertNullData();
}
专用静态无效测试\u insertInDscendingOrder(){
SortedLinkedList name=新的SortedLinkedList();
name.add(“v”);name.add(“b”);name.add(“a”);name.display();
}
专用静态无效测试_insertInAscendingOrder(){
SortedLinkedList name=新的SortedLinkedList();
名称。添加(“a”);名称。添加(“b”);名称。添加(“c”);名称。添加(“d”);
name.display();
}
专用静态空隙试验\u insertTw