18. 刪除鏈表的節點
難度簡單12收藏分享切換爲英文關注反饋
給定單向鏈表的頭指針和一個要刪除的節點的值,定義一個函數刪除該節點。
返回刪除後的鏈表的頭節點。
注意:此題對比原題有改動
示例 1:
輸入: head = [4,5,1,9], val = 5 輸出: [4,1,9] 解釋: 給定你鏈表中值爲 5 的第二個節點,那麼在調用了你的函數之後,該鏈表應變爲 4 -> 1 -> 9.
示例 2:
輸入: head = [4,5,1,9], val = 1 輸出: [4,5,9] 解釋: 給定你鏈表中值爲 1 的第三個節點,那麼在調用了你的函數之後,該鏈表應變爲 4 -> 5 -> 9.
1.遍歷法
th:通過loop遍歷 找到等於val的節點 將上一個節點和要刪除節點的next節點相連接。
time:O(n)
space:O(1)
public ListNode deleteNode(ListNode head, int val) {
if(head == null || head.next == null){
return null;
}
//遍歷查找到Node.val = val的結點
ListNode root = head;
//如果是頭結點就是要刪除的節點 直接用root.next 指向根節點 返回即可
if(root.val == val){
head = root.next;
return head;
}
while(root.next != null){
if(root.next.val == val){
root.next = root.next.next;
return head;
}
root = root.next;
}
return head;
}
2.雙指針
th:一共兩種情況 1. 頭結點就是刪除的節點 直接返回head.next 即可。
2.刪除的節點在鏈表中某個位置。 一個pre節點 和 一個 cur節點 cur節點比pre節點快一步 找到刪除即可。
time:O(n)
space:O(1)
public ListNode deleteNode(ListNode head, int val) {
//如果是head節點 直接返回
if(head.val == val){
return head.next;
}
ListNode pre = head, cur = head.next;
//遍歷尋找
while(cur != null && cur.val != val){
pre = cur;
cur = cur.next;
}
if(cur!=null){
pre.next = cur.next;
}
return head;
}