【发布时间】:2023-03-16 05:08:01
【问题描述】:
我正在处理我的作业中的链表,一部分是从列表中删除最后一个元素,另一部分是用链表中的新元素替换一个元素。
我实际上很难弄清楚如何将它组合在一起,我对删除和替换进行了一些研究,结果并没有真正的帮助,但有一个与替换密切相关。
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 replace(int oldVal, int newVal)
关于替换的另一部分是这样的
/*********************************
// public void replace(int oldVal, int newVal)
// —replaces all occurrences of oldVal in the list with newVal.
//********************************
public void replace(int oldVal, int newVal)
{
IntNode oldval = new IntNode(oldVal,front);
IntNode newval = new IntNode(newVal,front);
if (front == null)
{
front = newval;
}
else
while (oldval.next != null)
{
oldval = oldval.next;
oldval.next = newval;
}
}
已更新,如果代码正确以允许我用链表中的新元素更改一个元素,仍然在苦苦挣扎。
public IntNode(int val, IntNode next)
{
this.val = val;
this.next = next;
}
除非我弄错了并且我不需要使用它。
结果应该允许我从列表末尾删除一个元素,并能够用新值替换旧值。
【问题讨论】:
-
能否展示调用 removeLast() 的代码以及 front 和 count 是如何定义的?
-
确定
java public static void dispatch(int choice) { int newVal; switch(choice) { .... case 7: //remove the last element list.removeLast(); break; -
前面和计数被定义
java public class IntList { private IntNode front; //first node in list private int count; //count all elements
标签: java replace linked-list nodes