【发布时间】:2020-10-26 19:10:09
【问题描述】:
我在使用 delete 和 insertAfter 方法时遇到问题,这些方法是执行操作并在操作成功(真)或不成功(假)时返回布尔值。 InsertAfter 方法会插入一个字符串但总是在同一个位置,Delete 方法总是会删除同一个节点。
private class StrNode {
String data;
StrNode next;
}
private StrNode head; // the head of the singly-linked list.
public StringList() {
head = null;
}
public void prepend(String s) {
var newNode = new StrNode();
// TODO: Adds an item to the start of the list.
newNode.data = s;
if(head == null) {
head = newNode;
}
else {
newNode.next = head;
head = newNode;
}
}
/**
* Inserts an item after the first instance of a key if the key exists.
*
* @param s the item to insert
* @param key the item in the list to insert after
* @return whether the insertion was successful
*/
public boolean insertAfter(String s, String key) {
// TODO: Inserts an item after the first instance of a key if the key exists.
var newNode = new StrNode();
StrNode current = head;
newNode.data = s;
if(head == null) {
head = newNode;
}
else if(current == newNode.next){
current.next = newNode;
current = newNode;
}
else {
newNode.next = current.next;
current.next = newNode;
}
return false;
}
/**
* Deletes the first instance of an item from the list.
*
* @param key the value of the item to delete from the list.
* @return whether the deletion was successful.
*/
public boolean delete(String key) {
// TODO: Deletes the first instance of an item from the list.
StrNode current = head;
StrNode sucNode = current;
if(current == null) {
sucNode = head.next;
head = sucNode;
return true;
}
else if(current.next != null) {
sucNode = current.next.next;
current.next = sucNode;
return true;
}
return false;
}
我想在三之后插入四的主要方法应该是:三、二、四、一。 但我得到:三、四、二、一
delete 方法只是删除实际上应该看起来像这样的四个:三、四、二 但我得到:三,二,一 主要:
public static void main(String[] args) {
StringList s = new StringList();
s.prepend("one");
s.prepend("two");
s.prepend("three");
System.out.println(s);
s.insertAfter("four", "three");
System.out.println(s);
System.out.println(s.delete("one"));
System.out.println(s);
}
【问题讨论】:
-
我以为我昨天看到了这个问题。你又发帖了?我清楚地记得 prepend() 方法,我觉得它是一个奇怪的方法名称。我会使用 addFirst()。无论如何,您应该包含 prepend() 方法的代码,因为这是您进行设置的方式。
-
是的,我的错,我想我会让事情更清楚,只是为了看看我正在尝试的方法,谢谢!
标签: java methods linked-list