添加到链接列表的末尾

时间:2019-02-24 02:42:10

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

我对链表有一个append方法,我想在链表中添加尾部,但是当新节点添加到列表中时,headNode和tailNode都成为新插入的节点。如何使headNode保持为输入到列表中的第一个节点,而不让它成为tailNode。

 public static void append()
{
 for(int x = 0; x < gradeArray.length; x++)
 {
   if(gradeArray[x] < 70)
   {
     StudentNode newNode = new StudentNode(nameArray[x], gradeArray[x], null);
     if(headNode == null)
     {
       headNode = newNode;
     }
     else
     {
       tailNode.nextNode = newNode;
     }
     tailNode = newNode;
}
 }
 }

2 个答案:

答案 0 :(得分:1)

我不确定您在犯什么错误,但是请看下面的代码是否工作正常。

    public class Grades {

    public static String[] nameArray = new String[50];
    public static int[] gradeArray = new int[50];

    public static StudentNode headNode;
    public static StudentNode tailNode;

    public static void append() {
        for (int x = 0; x < gradeArray.length; x++) {
            if (gradeArray[x] < 70) {

                String name = nameArray[x];
                int grade = gradeArray[x];
                StudentNode newNode = new StudentNode(name, grade, null);
                if (headNode == null) {
                    headNode = newNode;
                } else {
                    tailNode.nextNode = newNode;
                }
                tailNode = newNode;
            }
        }
    }

    public static void main(String[] args) throws java.lang.Exception {
        for (int i = 0; i < 50; i++) {
            nameArray[i] = "name-" + i;
            gradeArray[i] = i;
        }

        append();

        for(int i=0; i<50; i++) {
            nameArray[i] = "name-" + (i + 50);
            gradeArray[i] = i + 50;
        }

        append();

        System.out.println(headNode.toString());
        System.out.println(tailNode.toString());
    }
 }

 class StudentNode {

    public int grade;
    public String name;
    public StudentNode nextNode;

    public StudentNode(String n, int g, StudentNode sn) {
        name = n;
        grade = g;
        nextNode = sn;
    }

    public String toString() {
        return name + ", " + grade;
    }
}

即使您更改成绩和名称数组并再次运行append,它仍然可以保持正确的头绪。

Ideone link for running code

答案 1 :(得分:0)

Why did you append this statement ? tailNode = newNode;

Imagine, thread goes through by if(headNode == null) he assign newNode adress to headNode . After that, tailNode = newNode; is executed and tail pointing to newNode. Finally, tailNode and headNode point to the same object : newNode.

I think you have to delete this statement tailNode = newNode;