Hi I have the following code where I am trying to delete a link from a LinkedList. I am able to delete the node, but whenever I try to iterate through the list, it gives me the original count. Can someone please help me here?
//Code from a different Class where I have created an object of the LinkedList class
ll.deleteLinkNumber(6);
//Code from the LinkedList Class
public void deleteLinkNumber(int linkNumber) {
//Link lastLink = getLastLink();
Link currentLink = first;
Link firstLink = currentLink;
int linkCount = 1;
while (first != null) {
if (linkCount == linkNumber) {
first = first.nextLink.nextLink;
System.out.println("Deleted one link: " + linkCount);
}
else {
first = first.nextLink;
System.out.println("Not deleting: " + linkCount);
}
linkCount++;
}
first = firstLink;
System.out.println("dd" + first.nextLink.nextLink.nextLink.nextLink.nextLink.dataElementInt);
//first.nextLink.nextLink.nextLink = first.nextLink.nextLink.nextLink.nextLink.nextLink;
/*
int count = getLinkedListCount(first);
Link firstLink = first;
Link currentLink = first;
first.nextLink.nextLink.nextLink = first.nextLink.nextLink.nextLink.nextLink;
System.out.println("Count of initial list: " + count);
while (currentLink !=null) {
if (count-linkNumber != 1) {
currentLink = currentLink.nextLink;
System.out.println("Not deleting: " + count);
}
else {
currentLink = currentLink.nextLink.nextLink;
System.out.println("Deleted one link: " + count);
}
count--;
}
*/
}
public void printList() {
/*
In the class LinkedList, first is always the first link from the LEFT. For example below
ThirdLink->SecondLink->FirstLink.nextLink = null;
first = ThirdLink;
*/
Link currentLink = first;
int count = 1;
while (currentLink != null) {
currentLink.printLink(count);
count++;
currentLink = currentLink.nextLink;
}
}
}
This line:
first = first.nextLink
is modifying a field, even though you're meant to just be looping to find the right link. That seems like a very odd thing to do.
I'd expect to have something like:
public void deleteLinkNumber(int linkNumber) {
Link previous = null;
Link current = first;
for (int i = 0; i < linkNumber && current != null; i++) {
previous = current;
current = current.nextLink;
}
if (current == null) {
throw new IllegalArgumentException("No such link");
}
// Delete first link? Just change the head.
if (previous == null) {
first = first.nextLink;
return;
}
// Anything else - just change the link.
previous.nextLink = current.nextLink;
}
See more on this question at Stackoverflow