问题
I have to insert a new Node at the beginning of my linked list. After I switched the Data Packages I try to overwrite the Data of my first Node with the new Data. But if I do that, my Program changes the data-values of my first and second Node.
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);
}
}
回答1:
I think you're making this unnecessarily complex. To insert to the beginning of a linked list all you need to do is this:
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;
}
This code simply creates a new node, makes it the new first node, and makes it point to all of the nodes that already exist. So if you had nodes B->C->D, your end result will be A->B->C->D
来源:https://stackoverflow.com/questions/36678677/inserting-node-at-the-beginning-of-a-linked-list