gpt4 book ai didi

java - LinkedList从头开始,替换一个节点

转载 作者:行者123 更新时间:2023-12-01 06:10:08 24 4
gpt4 key购买 nike

我被分配了从头开始创建 LinkedList 的任务,我已经弄清楚如何编写在列表末尾添加节点的方法,但我仍然不知道如何替换节点。这是我到目前为止所拥有的:

public boolean replace(int element, int index) {
Node temp= new Node(pElement);
Node current = getHead();
if (!isEmpty()) {
for (int i = 0; i < index && current.getNext() != null; i++) {
current = current.getNext();
}
temp.setNext(noeudCourant.getNext());
noeudCourant.setNext(temp);

listCount++;
return true;
}
return false;
}

在“0 1 2 3 4 5 6 7 8 9 10”上使用aNode.replace(10, 4)

将使其成为

[0]->[1]->[2]->[3]->[4]->[10]->[5]->[6]->[7]->[8]->[9]->[10]

但我想要:

[0]->[1]->[2]->[3]->[10]->[5]->[6]->[7]->[8]->[9]->[10]

感谢任何帮助。

[编辑]我已经有一个工作方法 setData() 但我的作业禁止我使用它。我想要的基本上是这样的:

/image/OaW0T.png

最佳答案

这是您问题的简单解决方案:

package linkedlist;

class Node {
public Node next = null;
public int element;

public Node(int el) {
element = el;
}
}

class LinkedList {
public Node first = null;

public void add(Node node) {
if (first == null) {
first = node;
} else {
// Traverse to the last
Node cursor = first;

while (cursor.next != null) {
cursor = cursor.next;
}

cursor.next = node;
}
}

public void add(int[] elements) {
int len = elements.length;

for (int i=0;i < len;i++) {
add(new Node(elements[i]));
}
}

public boolean replace(int element, int index) {
Node cursor = first;
Node prev = null;

while (cursor != null && index >= 0) {
index--;
prev = cursor;
cursor = cursor.next;
}

if (index > 0) return false;

if (prev != null)
prev.element = element;

return true;
}

public void displayAll() {
Node cursor = first;
while (cursor != null) {
System.out.print(cursor.element + " ");
cursor = cursor.next;
}
System.out.println();
}
}

public class Main {

public static void main(String[] args) {
// Prepare elements
LinkedList linkedList = new LinkedList();
linkedList.add(new int[]{0,1, 2, 3, 4, 5, 6, 7, 8, 9, 10});

println("Display the initial linked list content:");
linkedList.displayAll();

println("After replace:");
linkedList.replace(10, 4);
linkedList.displayAll();

println("Done");
}

static void println(String msg) {
System.out.println(msg);
}
}

关于java - LinkedList从头开始,替换一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36232448/

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