gpt4 book ai didi

java - 单链表中节点的删除

转载 作者:行者123 更新时间:2023-12-02 01:12:11 25 4
gpt4 key购买 nike

while 循环只是遍历链表的头部并表示要删除它。但没有删除。我想删除中间的一个节点,但这也没有发生。

我尝试过 equals 方法,也尝试过compareTo 方法

//******************Deletion by Key***********************
//Method to delete a node in the Linked List by key
public static LinkedList deleteByKey(LinkedList list, String first, String last) {
//Store head node
Giftor currNode = new Giftor(null, null);
currNode = list.head;
Giftor prev = new Giftor(null, null);
//prev= null;
System.out.println("Deleting: " + first + " " + last);
System.out.println("currNode.firstName " + currNode.firstName);

//
//Case 1:
//If head node itself holds the key to be deleted
if(currNode != null && currNode.firstName.equals(first) && currNode.lastName.equals(last)) {
list.head = currNode.next;
System.out.println(first + " " + last + " found and deleted");
return list;
}

//
//CASE 2:
//If the key is somewhere other than head
//

// Search for the key to be deleted,
// keep track of the previous node
// as it is needed to change currNode.next
while (currNode != null && (currNode.firstName.compareTo(first) == 0
&& currNode.lastName.compareTo(last) == 0)) {
// If currNode does not hold key
// continue to next node
prev = currNode;
currNode = currNode.next;
}

//If the firstName and lastName were present, it should be at currNode
//Therefore the currNode should not be null
if(currNode != null) {
//Since the firstName/lastName is at currNode
//Unlink currNode from linked list
prev.next = currNode.next;
//Display the message
System.out.println(currNode.firstName + " " + currNode.lastName + " found and deleted");
}

//
// CASE 3: The key is not present
//

// If key was not present in linked list
// currNode should be null
if (currNode == null) {
// Display the message
System.out.println(currNode.firstName + " " + currNode.lastName + " not found");
}

// return the List
return list;

}//end of deleteByKey
LinkedList: 
Micheal Womack
Randall Womack
Rita Evans
Trent Beck
Chris Baird
Lisa Adams
Deleting: Rita Evans
currNode.firstName Micheal
Micheal Womack found and deleted
LinkedList:
Micheal Womack
Randall Womack
Rita Evans
Trent Beck
Chris Baird
Lisa Adams
LinkedList:
Micheal Womack
Randall Womack
Rita Evans
Trent Beck
Chris Baird
Lisa Adams
Deleting: Rita Evans
currNode.firstName Micheal
Micheal Womack found and deleted
LinkedList:
Micheal Womack
Randall Womack
Rita Evans
Trent Beck
Chris Baird
Lisa Adams

最佳答案

情况 2 中的 while 循环对我来说似乎是错误的。仅当当前节点的名字和姓氏 等于 firstlast 时,它才会进行迭代。因此,如果头节点不匹配,则循环体根本不会执行。如果确实匹配,情况 1 就已经解决了这个问题。

尝试将其更改为:

while (currNode != null && (!currNode.firstName.equals(first) 
|| !currNode.lastName.equals(last))) {
// If currNode does not hold key
// continue to next node
prev = currNode;
currNode = currNode.next;
}

关于java - 单链表中节点的删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57678493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com