Ant Design Vue自定義選單圖示時收起選單文字不隱藏問題
技術標籤:演算法
題目描述
給定單向連結串列的頭指標和一個要刪除的節點的值,定義一個函式刪除該節點。
返回刪除後的連結串列的頭節點。
注意:此題對比原題有改動
示例 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.
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
我的程式碼(雙指標法)
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head.val!=val)//要刪除的節點不是頭結點
{
ListNode pre=head;//記錄當前節點的前一個節點,噹噹前節點的val值等於傳入的val時,好改變pre的指向
ListNode cur= head.next;//,cur=head.next;
while(cur!=null)
{
if(cur.val==val)//如果當前節點的val值等於傳入的val值
{
pre.next=cur.next;//當前節點的前一個節點指向當前節點的後一個節點
//temp.next=temp.next.next;
return head;//找到val值,直接返回
}
else
{
pre=cur;//pre指標後移指向當前節點
cur=cur.next;//當前節點後移
}
}
return head;//返回頭結點
}
return head.next;
}
}
雙指標解法2
class Solution {
public ListNode deleteNode(ListNode head, int val) {
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;
}
}
作者:jyd
連結:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/solution/mian-shi-ti-18-shan-chu-lian-biao-de-jie-dian-sh-2/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。
單指標解法
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head == null) return null;
if (head.val == val) return head.next;
ListNode cur = head;
while (cur.next != null && cur.next.val != val)
cur = cur.next;
if (cur.next != null)
cur.next = cur.next.next;//如果cur.next是最後一個節點,那麼cur.next.next為null,沒毛病
return head;
}
}
遞迴解法
提到遞迴的模板,我們看下
public void recursion(引數0) {
if (終止條件) {
return;
}
可能有一些邏輯運算
recursion(引數1)
可能有一些邏輯運算
recursion(引數2)
……
recursion(引數n)
可能有一些邏輯運算
}
作者:sdwwld
連結:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/solution/shuang-zhi-zhen-he-di-gui-liang-chong-fang-shi-jie/
我們來定義一個遞迴的函式
public ListNode deleteNode(ListNode head, int val),
他表示的是刪除連結串列中值等於val的結點,那麼遞迴的終止條件就是當head等於空的時候,我們直接返回head,因為一個空的連結串列我們是沒法刪除的,也就是下面這樣
if (head == null)
return head;
如果head結點不等於空,並且head結點的值等於val,我們直接返回head結點的下一個結點
if (head.val == val)
return head.next;
否則也就是說頭結點是刪不掉的,我們就遞迴呼叫,從頭結點的下一個開始繼續上面的操作,直到刪除為止。
head.next = deleteNode(head.next, val);
return head;
完整程式碼如下
public ListNode deleteNode(ListNode head, int val) {
if (head == null)
return head;
if (head.val == val)
return head.next;
head.next = deleteNode(head.next, val);
return head;
}
作者:sdwwld
連結:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/solution/shuang-zhi-zhen-he-di-gui-liang-chong-fang-shi-jie/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。