我必须在链接列表的开头插入一个新节点。切换数据包后,我尝试用新数据覆盖第一个节点的数据。但如果我这样做,我的程序会更改我的第一个和第二个节点的数据值。
void insert(String iv_name, String iv_name_first, String iv_title, int iv_earning) {
if (this.first == null) {
this.first = new Node(new Data(iv_name, iv_name_first, iv_title, iv_earning, 0));
} else {
Node n = this.first;
Data last_n_data = getLast().data;
Data[] datas = new Data[getLast().data.getId()];
int j = 0;
while (n.next != null) {
datas[j] = n.data;
j++;
n = n.next;
}
j = 0;
n = this.first;
while (n.next != null) {
n.next.data = datas[j];
n.next.data.setId(datas[j].getId() + 1);
j++;
n = n.next;
}
n.next = new Node(new Data(last_n_data.getName_last(), last_n_data.getName_first(), last_n_data.getTitle(),
last_n_data.getEarning(), last_n_data.getId() + 1));
n.next.next = null;
this.first.data.setName_last(iv_name);
this.first.data.setName_first(iv_name_first);
this.first.data.setTitle(iv_title);
this.first.data.setEarning(iv_earning);
this.first.data.setId(0);
}
}
最佳答案
我认为你让事情变得不必要的复杂。要插入到链接列表的开头,您需要做的就是:
void insert(String iv_name, String iv_name_first, String iv_title, int iv_earning) {
Node toCreate = new Node(new Data(iv_name, iv_name_first, iv_title, iv_earning, 0));
toCreate.next = this.first;
this.first = toCreate;
}
此代码只是创建一个新节点,使其成为新的第一个节点,并使其指向所有已存在的节点。因此,如果您有节点 B->C->D,则最终结果将是 A->B->C->D
关于java - 在链表开头插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36678677/