一天一道LeetCode
本系列文章已全部上傳至我的github,地址:ZeeCoder‘s Github
歡迎大家關注我的新浪微博,我的新浪微博
我的個人博客已創建,歡迎大家持續關注!
一天一道leetcode系列依舊在csdn上繼續更新,除此係列以外的文章均遷移至我的個人博客
另外,本系列文章已整理並上傳至gitbook,網址:點我進
歡迎轉載,轉載請註明出處!
(一)題目
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
(二)解題
題目大意:刪除單向鏈表中的與給定值相等的節點。
解題思路:題目很簡單,但是需要注意一下幾點:
- 考慮到如果刪除頭節點需要更新頭節點
- 考慮連續刪除的情況
代碼實現如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* pre = NULL;
ListNode* p = head;
while(p){
if(p->val==val){//與給定值相等
while(p&&p->val==val) p=p->next;//連續相等的情況
if(pre==NULL) head = p;//如果需要刪除頭節點,則需要更新頭節點
else pre->next = p;
}
else{
pre = p;
p=p->next;
}
}
return head;
}
};