package com.dugstudio.SwordToOfferBook.Singleton.Interview;
/**
* @Author JH
* @CreateDate 18-6-8
* @Description 在O(1)時間內刪除鏈表節點
*/
class Node{
public Integer value;
public Node next;
}
public class DeleteNode {
public void deleteNode(Node head, Node p){
//當頭結點或者待刪除的節點爲空
if(p==null||head==null){
return;
}
Node q;
//若待刪除的節點爲尾節點
if (p.next==null){
q=head;
while(q!=null){
if (q.next==p)break;
q=q.next;
}
q.next=null;
return;
}
//將p的下一個節點q的值賦給p,讓p指向q的下個節點,刪除q
q=p.next;
p.value=q.value;
p.next=q.next;
q.next=null;
}
}
在O(1)時間內刪除鏈表節點
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.