一個鏈表,需要對它進行刪除操作,那麼怎麼在o(1)的時間複雜度內將其準確刪除呢?
其實,就是將某個node.value賦爲0,其左右的指針打斷再重連即可。關鍵是怎麼重連。
比如,我要刪除i節點,那麼讓h直接指向j節點即可。但是,找到h節點,要遍歷n次,不符合要求。所以,我們將j值複製到i處,再指向下下個點即可。
具體步驟如下:
1.判斷head與要刪除的點是否爲null,如果爲null,直接返回head。
2.如果刪除的就是head,那麼直接返回head.next (新的頭結點)
3.如果刪除的是最後一個點,則一個個遍歷,最後將末值賦爲0即可。
4.如果刪除的是中間節點,則先複製,再重新指向
5.寫一個輸出函數,寫一個主函數,創建鏈表即可復現。
public class Test13{
public static class ListNode{
int value;
ListNode next;
}
public static ListNode deleteNode(ListNode head,ListNode tobeDeleted){
// 如果輸入參數有空值就返回表頭結點
if (head == null || tobeDeleted == null) {
return head;
}
// 如果刪除的是頭結點,直接返回頭結點的下一個結點
if (head == tobeDeleted) {
return head.next;
}
//以下情況,至少有2個節點
//刪除的是最後一個點
if (tobeDeleted.next == null){
ListNode tmp = head;
while(tmp.next != tobeDeleted){//tmp的下一個節點只要不是待刪除的,都往下遍歷
tmp = tmp.next;
}
tmp.next = null;//找到了next爲待刪除的點,則將next賦值爲0,即刪除
}else {//如果刪除的是中間節點
tobeDeleted.value = tobeDeleted.next.value;
tobeDeleted.next = tobeDeleted.next.next;
}
return head;//返回刪除後的頭結點
}
/*
輸出鏈表的元素
@Param head 鏈表的頭結點
*/
public static void printList(ListNode head){
while(head!=null){
System.out.println(head.value + "->");
head = head.next;
}
System.out.println("null");
}
public static void main(String[] args) {
ListNode head = new ListNode();
head.value = 1;
head.next = new ListNode();
head.next.value = 2;
head.next.next = new ListNode();
head.next.next.value = 3;
head.next.next.next = new ListNode();
head.next.next.next.value = 4;
ListNode middle = head.next.next.next.next = new ListNode();
//或者這一步也行 head.next.next.next.next.value = 5;
middle.value =5;
head.next.next.next.next.next = new ListNode();
head.next.next.next.next.next.value = 6;
head.next.next.next.next.next.next = new ListNode();
head.next.next.next.next.next.next.value = 7;
head.next.next.next.next.next.next.next = new ListNode();
head.next.next.next.next.next.next.next.value = 8;
ListNode last = head.next.next.next.next.next.next.next.next = new ListNode();
head.next.next.next.next.next.next.next.next.value = 9;
// head = deleteNode(head,null);
// printList(head);
head = deleteNode(head,middle);
printList(head);
}
}
參考文獻:https://blog.csdn.net/a136522541/article/details/85320053