[英]How to get rid of a node in a single linked list in java with this function?
I have a function called findNode that takes in the data and returns the node in a linked list. 我有一个名为findNode的函数,该函数接收数据并返回链表中的节点。
//helper function that finds the nodes
private ListNode findNode(E toFind){
ListNode current = front;
while(current!=null){
if(toFind.equals(current.data)){
return current;
}
else{
current = current.next;
}
}
return null;
}
How would I use this to remove a node? 我将如何使用它删除节点?
You can try something like this: 您可以尝试如下操作:
Find Node
whose next
value is Node
that was result of find then update link between these nodes such as: 查找next
值为查找结果的Node
的Node
,然后更新这些节点之间的链接,例如:
//iterate over List
if(current.next = resultOfFindNode){
//exit loop
}
//outside of loop
current.setNext(resultOfFindNode.next);
Write a function called findPrevNode based on findNode that you can use to delete the node from the list, like this. 基于findNode编写一个名为findPrevNode的函数,您可以使用该函数从列表中删除该节点,如下所示。
ListNode deleteNode;
if (toFind.equals(front.next.data)) {
// Found at the front of the list, no prev pointer
deleteNode = front;
front = front.next;
}
else if ((prev = findPrevNode(toFind)) != NULL) {
// Found after the start of the list
deleteNode = prev.next;
prev.next = prev.next.next;
}
else {} // Not found
findPrevNode would look something like this: findPrevNode看起来像这样:
private ListNode findPrevNode(E toFind){
ListNode current = front;
if (current == NULL) return NULL;
while(current.next != null){
if(toFind.equals(current.next.data)){
return current;
}
current = current.next;
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.