Lincode在O(1)時間複雜度刪除連結串列節點
阿新 • • 發佈:2019-01-31
在O(1)時間複雜度刪除連結串列節點
給定一個單鏈表中的一個等待被刪除的節點(非表頭或表尾)。請在在O(1)時間複雜度刪除該連結串列節點。
您在真實的面試中是否遇到過這個題? Yes 樣例Linked list is 1->2->3->4
,
and given node 3
, delete the node in place 1->2->4
public class Solution {
/** @param node: the node in the list should be deletedt
* @return: nothing
*/
public void deleteNode(ListNode node) {
// write your code here
if(node.next!=null){
node.val=node.next.val; //將要刪除的下一個節點的值賦給要刪除的節點
node.next=node.next.next; //刪除要刪除的下一個節點。
}
}
}