我添加了插入功能,显示可以有人帮忙 我删除了那将非常感激。
public class Node
{
Object data;
Node next;
}
public class LkList {
public Node insertVar(Object var1, Node ls1) {
Node p = new Node();
p.data = var1;
p.next = ls1;
ls1 = p;
return ls1;
}
public Node deleteVar(Object var1, Node ls1){
// deletion function goes here
}
public void printL(Node ls1) {
System.out.print("The lklist of variables is: ");
Node p = ls1;
while (p != null) {
System.out.print("[" + p.data + "]" + "->");
p = p.next;
}
System.out.println();
}
}
答案 0 :(得分:1)
删除节点将仅删除其参考可访问性。 在您的情况下,您希望通过比较变量的给定值来删除节点。因此,从头节点开始,您必须比较每个节点的数据(具体来说是变量数据)。您必须比较两个Node的数据,然后简单地中断然后只需应用链接列表删除逻辑。这里唯一关注的是比较两个节点的数据。不要使用
比较节点.equals()方法
public Node deleteVar(Object var1, Node ls1) {
if (ls1.data.varName.equals(var1.varName) && ls1.data.varValue.equals(var1.varValue)) { // If it is the first node which is to be deleted
return ls1.next;
}
else {
Node prev = ls1;
while (prev.next != null) {
if (prev.next.data.varName.equals(var1.varName) && prev.next.data.varValue.equals(var1.varValue)) {
// skip the node by linking the previous one to the next one directly
prev.next = prev.next.next;
break;
}
}
return ls1;
}
}
答案 1 :(得分:-1)
根据您的代码和解释,我假设ls1
是您列表中的第一个节点,并且您要删除列表中var1
为其data
的第一个节点:
public Node deleteVar(Object var1, Node ls1)
{
if (ls1.data.equals(var1))
{
//simply pop the first node
return ls1.next;
}
else
{
Node prev = ls1;
while (prev.next != null)
{
if (prev.next.data.equals(var1))
{
// skip the node by linking the previous one to the next one directly
prev.next = prev.next.next;
break;
}
}
return ls1;
}
}