伙计们,我仍然遇到方法public void deleteLink(String data)
的麻烦,我需要删除给定Link
的指定String data
。我已经实现了它但仍然无法正常工作。请问smb请看一下deleteLink()
方法,看看有什么问题?其他方法都运行正常。提前谢谢!
package LinkedList;
public class Link{
public Link next;
private String data;
public Link(String data){
this.data = data;
this.next = null;
}
public void display(){
System.out.println(data);
}
public String getData(){
return this.data;
}
}
class LinkedList{
private Link firstLink;
public LinkedList(){
this.firstLink = null;
}
public boolean isEmpty(){
return (this.firstLink == null);
}
public void insert(String data){
Link newLink = new Link(data);
newLink.next = firstLink;
firstLink = newLink;
}
public Link deleteFirst(){
Link deletedOne = null;
if(isEmpty()){
System.out.println("The list is empty");
System.exit(0);
}
else{
deletedOne = firstLink;
firstLink = firstLink.next;
}
return deletedOne;
}
public boolean search(String data){
if(isEmpty()){
System.out.println("The list is empty");
System.exit(0);
}
else{
Link current = firstLink;
while(current != null){
if(current.getData().equals(data)){
return true;
}
else{
current = current.next;
}
}
}
return false;
}
public void deleteLink(String data){
if(isEmpty()){
System.out.println("The list is empty.");
System.exit(0);
}
else{
Link current = firstLink;
Link previous = firstLink;
while(current != null){
if(current.getData().equals(data)){
previous = current.next;
break;
}
else{
previous = current;
current = current.next;
}
}
}
}
public void displayList(){
if(isEmpty()){
System.out.println("The list is empty");
System.exit(0);
}
else{
Link current = firstLink;
while(current != null){
current.display();
current = current.next;
}
}
}
}
答案 0 :(得分:3)
作业
previous = current.next;
不会更改链接列表中的任何内容。
您应该进行如下任务:
previous.next = current.next;
这将使被删除节点之前的节点指向被删除节点之后的节点。
当然,您也没有处理被删除节点是第一个节点的情况。这种情况应该单独处理。
public void deleteLink(String data){
if(isEmpty()){
System.out.println("The list is empty.");
System.exit(0);
}
else{
if (firstLink.getData().equals(data)) {
firstLink = firstLink.next;
} else {
Link current = firstLink.next;
Link previous = firstLink;
while(current != null){
if(current.getData().equals(data)){
previous.next = current.next;
break;
} else {
previous = current;
current = current.next;
}
}
}
}
}