【发布时间】:2023-01-30 05:25:03
【问题描述】:
我创建了一些带有 lastNode 指向头的节点。 在 removeCycle 方法中,当我尝试使 lastNode(i,e prev).next = null 时,首先检测到 lastNode 然后出错
public class loopsRemove {
public static class Node{
int data;
Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
public static Node Head;
public static Node Tail;
public static int count =0;
public static int removeCycle(){
Node slow = Head;
Node fast = Head;
boolean Cycle = false;
while(fast !=null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
count++;
if(slow == fast){
Cycle =true;
break;
}
}
if(Cycle == false){
return 0; //No Cycle and come out of function (int type is just to observe where function is returning
}
slow = Head;
Node prev=null; //to track previous of fast
while(slow != fast){
prev = fast;
slow = slow.next;
fast = fast.next; //speed is same as slow now
}
prev.next =null; //Making endNode.next to null
return 1; //int return is just to check weather my code is returning here or above
}
public static void main(String[] args) {
Head = new Node(3);
Head.next = new Node(4);
Head.next.next = new Node(5);
Head.next.next.next = new Node(6);
Head.next.next.next.next = Head; //cycle formed
System.out.println(removeCycle());
System.out.println(Head.next.next.next.next.data); // null is expected at the last node if removeCycle works correctly
}
}
预期输出: 1个 无效的
当前输出: 线程“main”中的异常 java.lang.NullPointerException:无法分配字段“next”,因为“prev”为空 在 loopsRemove.removeCycle(loopsRemove.java:44) 在 loopsRemove.main(loopsRemove.java:55)
【问题讨论】:
标签: java algorithm data-structures linked-list