请帮我理解方法删除(带指定值)如何工作?
除了这一点,我理解了所有事情。
我写了方法删除,但是不明白链接“上一个”中的下一个更改字段如何权衡链接首先,我知道下一个链接将被遗漏,但是此链接也将在第一个列表中丢失。(这意味着我不明白参考类型是如何工作的)
package Book.LinkedList;
/**
* Created by Сергей on 06.07.2015.
*/
public class Link {
Link(int serial) {
this.serial = serial;
next = null;
}
private int serial;
private Link next;
public void setSerial(int serial) {
this.serial = serial;
}
public int getSerial() {
return serial;
}
public void setNext(Link tmp) {
next = tmp;
}
public Link getNext() {
return next;
}
public void display() {
System.out.print(serial + " ");
}
}
package Book.LinkedList;
public class LinkList {
LinkList() {
first = null;
}
private Link first;
public boolean isEmpty() {
return first == null;
}
public void insertFirst(int serial) {
Link newLink = new Link(serial);
if(first == null ) { newLink.setNext(null); }
else {
newLink.setNext(first);
}
first = newLink;
}
public void deleteFirst(){
if( isEmpty() == false){
first = first.getNext();
System.out.println("The link was successfully deleted!");
}
else {
System.out.println("The LinkList is empty, we can't delete element!");
}
}
public boolean find(int key) {
Link current = first;
if (current == null) {
System.out.println("The list is empty.");
return false;
}
do {
if (current.getSerial() == key) {
return true;
}
else {
current = current.getNext();
}
}
while (current != null);
return false;
}
// delete chosen/ selected element
// пока нихера не понятно как данное удаление влияет именно на first, почему удаляется из first
public void delete(int key) {
Link previous = null;
Link current = first;
if (current == null) {
System.out.println("The list is empty.");
return;
}
do {
if (current.getSerial() == key) {
if(previous == null) { first = first.getNext(); return;}
else {
previous.setNext(current.getNext());
return;
}
}
else {
previous = current;
current = current.getNext();
}
}
while (current != null);
System.out.println("There isn't element with entered serial;");
}
public void displayList() {
Link current = first;
while(current != null) {
current.display();
current = current.getNext();
}
System.out.println("The linkList was successfully displayed");
}
}
答案 0 :(得分:3)
你可以在视觉上更好地想象它:
我们让next
链接跳过链中的一个步骤,然后我们只需删除不再需要的节点。虽然在这种情况下我们有点误导,因为我们从不直接调用删除。我们只是删除节点的所有引用,因此垃圾收集器会在一段时间后删除它。
first = first.next()
和完成,您需要注意的是,在 done 突出显示的两种情况下,节点都会丢失所有引用。