gpt4 book ai didi

java - 如何修复我的代码(SinglyLinkedList 类)以便删除方法在正确的索引处删除?

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

如何修复我的代码( SinglyLinkedList 类),以便 remove方法有效吗?我尝试删除索引 0 处的内容,但没有删除“美国”,而是删除了索引 2 处的“葡萄牙”。当我尝试在索引 1 处删除时,它确实可以正常工作。如有任何帮助,我们将不胜感激。

class SinglyLinkedList<E> { //---------------- nested Node class
private static class Node<E> {
private E element;
private Node<E> next;

public Node(E e, Node<E> n) {
element = e;
next = n;
}

public E getElement() {
return element;
}

public Node<E> getNext() {
return next;
}

public void setNext(Node<E> n) {
next = n;
}
}

private Node<E> head = null;
private Node<E> tail = null;
private int size = 0;

public SinglyLinkedList() {
}

public int size() {
return size;
}

public boolean isEmpty() {
return size == 0;
}

public E first() {
if (isEmpty()) return null;
return head.getElement();
}

public E last() {
if (isEmpty()) return null;
return tail.getElement();
}
// update methods

public void addFirst(E e) {
head = new Node<>(e, head);
if (size == 0)
tail = head;
size++;
}

public void addLast(E e) {
Node<E> newest = new Node<>(e, null);
if (isEmpty())
head = newest;
else
tail.next = newest;
tail = newest;
size++;
}

public void printLinkedList() {
Node<E> temp = head;
for (int i = 0; i < size; i++) {
System.out.println(temp.getElement());
temp = temp.next;
}
}

public void remove(int index) {
//Node<E> newest = new Node(e, null);
Node<E> current = head;
for (int i = 0; i < index - 1; i++) {
current = current.next;
current = current.getNext();
}
current.next = current.next.next;
size--;
}

public void add(int index, E e) {
Node<E> newNode = new Node<>(e, null);
if (index == 0) {
newNode.next = head;
head = newNode;
} else {
Node<E> current = head;
for (int i = 1; i < index; i++) {
current = current.next;
}
Node<E> tmp = current.next;
current.next = newNode;
newNode.next = tmp;
}
size++;
}
}

public class SinglyLinkedListTest {
public static void main(String args[]) {
SinglyLinkedList<String> list = new SinglyLinkedList();

list.addLast("USA");
list.addLast("America");
list.addLast("portugal");
System.out.println(" ");
list.printLinkedList();
list.remove(0);
System.out.println(" ");
list.printLinkedList();
list.removeLast();
System.out.println(" ");
list.printLinkedList();
list.add(2, "hello");
System.out.println(" ");
list.printLinkedList();
}
}

最佳答案

删除头部时,需要重新分配列表的head属性。一个简单的解决方案是添加一个条件来处理这种特殊情况:

public void remove(int index) {
size--;

if (index == 0) {
head = head.next;
return;
}

Node<E> current = head;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}

请注意,我从原始代码中删除了 current = current.getNext();,就在 current = current.next; 之后,因为这是一个错误,跳过每个第二个元素。

关于java - 如何修复我的代码(SinglyLinkedList 类)以便删除方法在正确的索引处删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46955523/

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