我的删除(节点p)方法有问题,我几乎已经完成了它,但每当我尝试编译它时,它说先前可能没有先前初始化。具体在if下面这个方法中的if语句。我是链接列表的新手,所以我只是想练习正确的语法。任何帮助都是极好的。谢谢你们。
public Node delete(Node p)
{
Node current, previous;
current = head.next;
while (current.info != p.info && current.next != null)
{
previous = current;
current = current.next;
}
if (current.info == p.info)
{
previous.next = current.next;
//this previous here is what is giving me trouble
}
return current;
}
//故障方法结束,整个代码的开始
public class LinkedList
{
Node head;
public class Node
{
int info;
Node next;
Node(int d)
{
info = d;
next = null;
}
}
public void insertAfter(Node prevnode, int new_info)
{
if (prevnode == null)
{
System.out.println("The given previous node cannot be null");
return;
}
Node newnode = new Node(new_info);
newnode.next = prevnode.next;
prevnode.next = newnode;
}
public void insertEnd(int new_info)
{
Node newnode = new Node(new_info);
if (head == null)
{
head = new Node(new_info);
return;
}
newnode.next = null;
Node last = head;
while(last.next != null)
{
last = last.next;
}
last.next = newnode;
return;
}
public void insertFirst(int new_info)
{
Node newnode = new Node(new_info);
newnode.next = head;
head = newnode;
}
public Node delete(Node p)
{
Node current, previous;
current = head.next;
while (current.info != p.info && current.next != null)
{
previous = current;
current = current.next;
}
if (current.info == p.info)
{
previous.next = current.next;
}
return current;
}
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.info + " ");
tnode = tnode.next;
}
}
public static void main(String[] args)
{
LinkedList slist = new LinkedList();
slist.insertEnd(6);
slist.insertFirst(7);
slist.insertFirst(1);
slist.insertEnd(4);
slist.insertAfter(slist.head.next, 8);
System.out.println("Top Ten Gaming Scores Are: ");
slist.printList();
}
}
答案 0 :(得分:0)
如果您的while循环中的条件:
while (current.info != p.info && current.next != null)
永远不会评估为true,您不进入循环,并且警告说previous
在您使用它时可能无法初始化。
在if语句中使用之前,应确保检查previous != null
。
答案 1 :(得分:0)
您必须始终初始化local variables
。在while块之前设置previous =null
将解决您的问题。
public Node delete(Node p)
{
Node current;
Node previous =null;
current = head.next;
while (current.info != p.info && current.next != null)
{
previous = current;
current = current.next;
}
if (current.info == p.info)
{
previous.next = current.next;
//this previous here is what is giving me trouble
}
return current;
}