Give a head node of a link list, please remove the node with the target value from the list. Then return pointer of list head node.
給一個link list的head node,還有一個target value,請你從link list中刪掉有target value的那些node. 然後回傳處理過後的list的head。
ps.假設list中沒有重複的value
e.g.
1->2->3->4, target value=3, 刪完後list變成1->2->4
然後return list head, 也就是 node 1的address.
1->2->3->4, target value=1, 刪完後list變成2->3->4
然後return list head, 也就是 node 2的address.
[思路]
要做三件事
1.找到target node
2.刪掉target node
3.return head node
1.找到target node:
用while loop和next pointer,不停地探索下一個人,直到該人value = target value
2.刪掉target node:
target node一定有它的previous node,將previous node的next pointer指向target node的下一個node,維持list的連接性。最後把target node刪掉。
e.g.
1->2->3->4, target value=3
previous node = node 2, 將node 2的next pointer指向4
1->2->4<-3
然後把node 3刪掉,大功告成
1->2->4
你有沒有覺得那裡聽起來怪怪的? 有耶! node 1沒有previous node耶!
這是本題重點,node 1沒有pre node,上述做法無法套用在node 1,這該怎麼解決呢?
當然你可以在function開頭特別偵測這個case,額外寫一套方法處理,但這邊教你更棒的方法,叫做dummy head node。
就是創造一個dummy head node 'D',把它放到list的最前方,讓list變成
D->1->2->3->4
今天假設你要刪掉node 1,就可以套用上述方法,把list變成D->2->3->4
然後回傳D的next pointer內的值,也就是node 2的address,也就是real list head address。
這方法好在code寫起來清爽,"刪除target node"的方式不再需要分成 head node/not head node兩種case。
3.return head node
第二步的最後說過了
你只要return dummy.next;
就可以了
給一個link list的head node,還有一個target value,請你從link list中刪掉有target value的那些node. 然後回傳處理過後的list的head。
ps.假設list中沒有重複的value
e.g.
1->2->3->4, target value=3, 刪完後list變成1->2->4
然後return list head, 也就是 node 1的address.
1->2->3->4, target value=1, 刪完後list變成2->3->4
然後return list head, 也就是 node 2的address.
[思路]
要做三件事
1.找到target node
2.刪掉target node
3.return head node
1.找到target node:
用while loop和next pointer,不停地探索下一個人,直到該人value = target value
2.刪掉target node:
target node一定有它的previous node,將previous node的next pointer指向target node的下一個node,維持list的連接性。最後把target node刪掉。
e.g.
1->2->3->4, target value=3
previous node = node 2, 將node 2的next pointer指向4
1->2->4<-3
然後把node 3刪掉,大功告成
1->2->4
你有沒有覺得那裡聽起來怪怪的? 有耶! node 1沒有previous node耶!
這是本題重點,node 1沒有pre node,上述做法無法套用在node 1,這該怎麼解決呢?
當然你可以在function開頭特別偵測這個case,額外寫一套方法處理,但這邊教你更棒的方法,叫做dummy head node。
就是創造一個dummy head node 'D',把它放到list的最前方,讓list變成
D->1->2->3->4
今天假設你要刪掉node 1,就可以套用上述方法,把list變成D->2->3->4
然後回傳D的next pointer內的值,也就是node 2的address,也就是real list head address。
這方法好在code寫起來清爽,"刪除target node"的方式不再需要分成 head node/not head node兩種case。
3.return head node
第二步的最後說過了
你只要return dummy.next;
就可以了
---
[Code]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode d(0, head);
ListNode *pCur = head, *pPrev=&d;
while(pCur!=NULL)
{
if(pCur->val == val)
{
pPrev->next = pCur->next;
delete pCur;
pCur = pPrev->next;
continue;
}
pPrev=pCur;
pCur=pCur->next;
}
return d.next;
}
};