构建链表java

时间:2018-03-13 16:59:26

标签: java algorithm data-structures linked-list

我正在尝试根据用户的输入在java中构建链接列表。 但是,似乎我得到的返回列表总是通过最后一个节点而不是第一个节点引用,这使得它对我来说不可行且无益。我尝试通过引用第一个节点-pos并返回引用来解决它,但它没有帮助。例如,对于输入1,2,3,4,当尝试打印链表时,它只打印4。 代码

//input : The function gets values
//output : The function builds a linked list with the given numbers
public static Node<Integer> buildList(){
    int num;
    System.out.println("Enter values for the linked list(-999 to stop)");
    num=reader.nextInt();
    Node<Integer> list=new Node<Integer>(num);
    Node<Integer> pos=list;
    while(num!=-999){
        num=reader.nextInt();
        if(num!=-999){
            Node<Integer> newNode=new Node<Integer>(num);
            newNode.setNext(list);
            list=newNode;
        }
    }
    return pos;
}

任何人都知道我做错了什么?我会非常感谢你的帮助。

3 个答案:

答案 0 :(得分:2)

您没有在后面添加新条目。 问题出在这个

 Node<Integer> newNode=new Node<Integer>(num);
 newNode.setNext(list);
 list=newNode;

此代码在链接列表的 head 处添加新节点。在方法结束时,返回引用 pos ,它是对您插入的第一个节点(链接列表中的最后一个节点)的引用。如果您在函数末尾返回对 newNode 的引用,那么您将拥有

4->3->2->1

这是一个在链表末尾添加新节点的正确版本

 Node<Integer> newNode = new Node<Integer>(num);
 list.setNext(newNode); //Link previous node to current node.
 list = newNode;

注意:当用户输入-999作为第一个号码时,您必须注意这种情况。在这种情况下,您仍然会创建一个节点(如果这是你想要的那就没关系。)

答案 1 :(得分:0)

Rahter比使用Node对象,为什么不使用LinkedList

您的代码如下:

//input : The function gets values
//output : The function builds a linked list with the given numbers
public static LinkedList<Integer> buildList(){
  int num = 0;      
  LinkedList<Integer> list = new  LinkedList<Integer>();
  while (num!=-999){
    System.out.println("Enter values for the linked list(-999 to stop)");
    num=reader.nextInt();
    if(num!=-999){
        list.add(num)
    }
  }
  return list;
}

答案 2 :(得分:0)

首先,您不应使用Node<>,而应使用List<>。 在您的情况下,它是List<Integer> list = new LinkedList<>();

第二个问题是您在所有迭代中创建一个新列表。在循环之前,您应该只使用new

此代码可以使用:

public static List<Integer> buildLitst() {
    List<Integer> list = new LinkedList<>();
    System.out.println("Enter values for the linked list (-999 to stop)");
    int number = reader.nextInt();

    while (number != -999) {
        list.add(number);
        number = reader.nextInt();
    }

    return list;
}