gpt4 book ai didi

java - 双向链表 - 头在变化而我没有改变它

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:42 24 4
gpt4 key购买 nike

问题出在 DLinkedList 类中的 findA 方法。该方法显然改变了我的 head.next 指向 tmp.next我创建了一个列表 {0,1,2,3,4,5,6,7,8,9}我用过

findA(9)

并且我的列表缩小到 {9},尽管无论给定值是否在我的列表中(true 或 false),函数都会给出正确的结果

另一方面,我的 find 方法运行良好,两者之间的唯一区别是我在 findA 中使用 Node tmp = head和 Node tmp = head.next in find

下面是完整的代码片段。我意识到有些实现非常不专业。任何对此的评论将不胜感激

public class Node <T extends Comparable<T>> {
T data;
Node prev;
Node next;

Node(){
}

Node(T val){
data = val;
} }

public class DLinkedList<T extends Comparable<T>> {
Node head;
Node tail;

DLinkedList(){
head = new Node();
tail = new Node();
tail.prev = head;
}

void insertInOrder(T value){
Node insert = new Node(value);
if(head.next==null){
head.next = insert;
insert.prev = head;
insert.next = tail;
tail.prev = insert;
}
else{
insert.prev = tail.prev;
tail.prev.next = insert;
tail.prev = insert;
insert.next = tail;
}
}

boolean find (T value){
boolean result = false;
Node tmp = head.next;
if (head!=null){
while(tmp!=null){
if(tmp.data.compareTo(value)!=0){
tmp = tmp.next;
}
else{
result = true;
break;
}
}
}
return result;
}

boolean findA (T value){
boolean result = false;
Node tmp = head;
if (head!=null){
while(tmp.next!=null){
if(tmp.next.data.compareTo(value)!=0){
tmp.next = tmp.next.next;
}
else{
result = true;
break;
}
}
}
return result;
}

void deleteA(T value){
Node tmp = head.next;

while(tmp.data.compareTo(value)!=0){
tmp = tmp.next;
}
if(tmp!=tail){
if(tmp==head.next)
head = tmp.next;
else
tmp.prev.next = tmp.next;

if (tmp==tail)
tail = tmp.prev;
else
tmp.next.prev = tmp.prev;
}






}
void delete(T value){
Node tmp = head.next;
if(find(value)){
while(tmp!=tail){
if(tmp.data.compareTo(value)!=0){
tmp = tmp.next;
}
else{
tmp.prev.next = tmp.next;
tmp.next.prev = tmp.prev;

break;
}
}
}
}

@Override
public String toString(){
Node tmp = head.next;
String result = "";
while(tmp!=tail){
System.out.println(tmp.data);
tmp = tmp.next;
}
return result;
} }

public class ListCheck {

public static void main(String[] args) {
DLinkedList list = new DLinkedList();
DLinkedList listA = new DLinkedList();
for(int i=0; i<10; i++){
list.insertInOrder(i);
listA.insertInOrder(i);
}
System.out.println(listA.findA(9));
System.out.println(list.find(9));
listA.toString();
System.out.println("");
list.toString();
} }

最佳答案

在你的 findA 中,你移动 tmp 的方式是通过执行

tmp.next = temp.next.next

通过这种方式,您将销毁当前指针并将其重新路由到下一个节点(java 的浅拷贝):

tmp--->[node1]--->[node2] 更改为 tmp--->[node2]

因此,在操作结束时,您的链表只剩下最后一个节点。

将其更改为tmp = tmp.next会有所帮助

关于java - 双向链表 - 头在变化而我没有改变它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42172612/

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