从“链接列表”中删除元素
原标题:Removing element from `LinkedList`
folks, my code has to remove a certain element from the list. It has to remove all of the occurences of the list. For example, if I d like to remove "3" and the input is:
1
2
3
4
3
5
then the output should be:
1
2
4
5
But my code only removes the last occurence of the element as it can be seen when I run my code:
3
4
3
2
1
After removing element 3
4
3
2
1
Could smb please help me out with that? THanks in advance!
public void removeElements(String number){
if(isEmpty()){
System.out.println("The list is empty!");
}
else{
if(firstLink.data.equals(number)){
firstLink = firstLink.next;
}
else{
Link current = firstLink.next;
Link previous = firstLink;
while(current != null){
if(current.data.equals(number)){
previous.next = current.next;
break;
}
else{
previous = current;
current = current.next;
}
}
}
}
}
问题回答
Your loop to remove elements is breaking on the first match. Maybe something like the following would work better. When current is a match, update previous.next but leave previous pointing at the previous node, and when it s not a match, update previous to point to the current node.
while (current != null) {
if (current.data.equals(number)) previous.next = current.next;
else previous = current;
current = current.next;
}
Remove the break, your loop is breaking after it gets into it for the first time.
Another point is, it is falling in your if(firstLink.data.equals(number)) and completely ignoring the else block. You should not have that block in else. It should be outside.
if(firstLink.data.equals(number)){
firstLink = firstLink.next;
}
Link current = firstLink.next;
Link previous = firstLink;
while(current != null){
if(current.data.equals(number)){
previous.next = current.next;
} else {
previous = current;
current = current.next;
}
}
What you can do is iterate through the entire loop and check if the value of the element matches the searched value. If it does then you can use remove that element. I won t give away the solution to this but I can provide you with the algorithm.
for(int i = 0; i < length of list; i++)
{
if(ith element of the list == value to be removed)
//remove the ith term using .remove(i) method
}
What you could do is make a new collection containing all the values you want to remove from the LinkedList, and then call removeAll on the list:
ArrayList numbersToRemove = new ArrayList();
numbersToRemove.add("3");
list.removeAll(numbersToRemove);
This way, if you want to remove multiple numbers later on, you can just add them to numbersToRemove.
Some of the other answers are a bit simpler and more straightforward, though, so use them if they make sense, like iterating through the list and removing any elements that match the element you are removing. The only problem with this is that you will get a ConcurrentModificationException if you modify the list while iterating through the list using the object : list syntax, and will probably get an index out of range exception if you iterate through it using indices, so you will probably need to do something like this instead:
while (list.contains("3")) {
ll.remove("3");
}
You can use a recursive approach to remove the nodes with given value.
Base condition -> return NULL if currentNode=NULL
At currentNode, we will check if its valid node or not,
if its valid Node (i.e currentNode s value != given value) then we will set its "next" by nextValidNode from the list ahead of it and then will return currentNode
if its not a valid node((i.e currentNode s value == given value) then, we have to simply return the nextValidNode from the list ahead of it
Here is the C++ implementation of the approach I discussed above, just pass head of list and value to the function:
ListNode* removeElements(ListNode* currentNode, int val) {
// base condition
if (currentNode == NULL) return NULL;
// find nextValidNode
ListNode* nextValidNode = removeElements(currentNode->next, val);
// currentNode is NOT VALID node
if (currentNode->val == val) {
return nextValidNode;
}
// currentNode is VALID node
else {
currentNode->next = nextValidNode;
return currentNode;
}
}
where ListNode is defined like this:
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
public void removeElement(String number) {
if (head == null) {
return; // The list is empty, nothing to remove
}
// Handle removal if the element to remove is at the head
while (head != null && head.data.equals(number)) {
head = head.next;
size--;
}
// Now ensure the head is not the target, move on to the rest of the list
Node prev = head;
Node current = head.next;
while (current != null) {
if (current.data.equals(number)) {
// Skip the current node to remove it
prev.next = current.next;
size--; // Update the size of the list
if (prev.next == null) { // If removed node was the tail
tail = prev; // Update the tail
}
} else {
// Move prev to current if current node is not removed
prev = current;
}
current = current.next; // Move to the next node
}
}
相关问题
Spring Properties File
Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...
What do you say of chopping type-4 UUID in this manner
Check this,
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
String value = (""+UUID.randomUUID().getLeastSignificantBits()).substring(3, ...
combining decorator and state pattern in java - question about OO design
I am in the middle of solving a problem where I think it s best suited for a decorator and a state pattern. The high level setting is something like a sandwich maker and dispenser, where I have a set ...
Unable to execute stored Procedure using Java and JDBC on SQL server
I have been trying to execute a MS SQL Server stored procedure via JDBC today and have been unsuccessful thus far. The stored procedure has 1 input and 1 output parameter. With every combination I ...
Logging a global ID in multiple components
I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications.
[App A] -> [App B] -> [App C]
We set a ...
Java Library Size
If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is:
How will the larger, mostly unused ...
How to get the Array Class for a given Class in Java?
I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this:
Class arrayOfFooClass = java.lang....
SQLite , Derby vs file system
I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database.
How hard is it to migrate ...