folks, I'm having trouble with removing a specified Link from a LinkedList. For example, if I have:
"A" --> "B" --> "C"
and would like to remove a Link "B", so the result would be:
"A" --> "C"
I'm having troubles with how to get the previous Link "A" and reference to "C". Can anyone help me out with that? The method is:
public void delete(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.getNext();
}
else{
previous = current;
current = current.getNext();
}
}
}
}
Class Link
package LinkedList;
public class Link{
private String data;
private Link next;
public Link(String data){
this.data = data;
}
public void display(){
System.out.println(data);
}
public String getData(){
return this.data;
}
public Link getNext(){
return this.next;
}
}
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);
Link newLinkNext = newLink.getNext();
newLinkNext = firstLink;
firstLink = newLink;
}
public Link deleteFirst(){
if(isEmpty()){
return null;
}
else {
Link deletedOne = this.firstLink;
Link nextLink = firstLink.getNext();
firstLink = nextLink;
return deletedOne;
}
}
public void delete(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.getNext();
}
else{
previous = current;
current = current.getNext();
}
}
}
}
"B"?whileloop - why not remember the previous value each time through the loop?previous.next = current.getNext()and notprevious = current.getNext(). Should probably put a check ifcurrent == firstLinkand deal with that appropriately.