1
노드가있는 단일 연결 목록에서 노드를 제거하는 프로그램을 작성했습니다.단일 연결 목록 중간에 노드 삭제
public class Solution {
/**
* @param node: the node in the list should be deleted
* @return: nothing
*/
public void deleteNode(ListNode node) {
// write your code here
// if node.next==null, we cannot delete the current node without given the previous node
if(node == null || node.next == null) return;
ListNode next = node.next;
node.val = next.val;
node.next = next.next;
// I wonder if this link needs to be removed as well
next.next = null;
}
}
문제는 매우 간단합니다. 그러나 많은 온라인 코드 샘플에는 내가 작성한이 줄이 포함되어 있지 않습니다.
next.next = null;
이 줄이 없으면 노드가 이미 제거되었습니다. 그 다음에는 "다음"을 가리키는 것이 없지만 "다음"은 여전히 next.next를 가리 킵니다. next.next = null을 설정하지 않으면 Java 가비지 수집기가이 삭제 된 노드를 제거할까요?
'node'를 지우고 싶다면'next.next'는 실제 노드에서 세 번째 노드 인'node.next.next'입니다. 삭제해서는 안됩니다. – 11thdimension