我无法创建一种通过String“ key”参数删除节点的方法。给我一个名为key的字符串作为参数。
所以,这是我的Node.java
public class Node {
public Node next;
public Node prev;
public String data;
public void setData(String data) {
this. data = data;
}
public String getData() {
return this.data;
}
}
这是我的DoubleLinkedList.java:
public class DoubleLinkedList {
public Node head;
public Node tail;
public int size;
public DoubleLinkedList() {
this.head = head;
this.tail = tail;
this.size = 0;
}
public void addFirst(String data) {
Node newNode = new Node();
newNode.setData(data);
if (head == null && tail == null) {
head = newNode;
tail = head;
} else {
head.prev = newNode;
newNode.next = head;
head = newNode;
}
size++;
}
public void deleteFirst() {
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
head.prev = null;
}
size--;
}
public void deleteLast() {
if (head == tail) {
head = null;
tail =null;
} else {
tail = tail.prev;
tail.next =null;
}
size--;
}
public boolean find(String key) {
Node temp = head;
while (!temp.getData().equals(key)) {
if(temp.next == null) {
return false;
}
temp = temp.next;
}
return true;
}
public void deleteByKey(Node key) {
/*CODE HERE
*/
}
public void display() {
if(head != null) {
Node temp = head;
while (temp != null) {
System.out.println(temp.getData()+ " ");
temp = temp.next;
}
} else {
System.out.println("Double LinkedList anda kosong!");
}
}
public boolean isEmpty() {
return (head == null && tail == null);
}
public void makeEmpty() {
head = null;
tail = null;
}
}
我要删除一个与“ key”元素相同的节点:
列表(之前):A B C D E F G
DeleteByKey(D);
列表(之后):A B C E F G
答案 0 :(得分:0)
public void deleteByKey(String key) {
Node temp = head;
Node temp1 = null;
while (!temp.getData().equals(key)) {
if(temp.next == null) {
System.out.println("data not found");
break;
}
temp1=temp;
temp = temp.next;
}
if(temp.getData().equals(key)) {
temp=temp.next;
temp.prev=temp1;
temp1.next=temp;
}
}