题外话:
最近突然降温,真的好冷 // 呼~呼~冷风吹~
题目:
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
题意:
输入链表和特定值val,输出要求将链表中的所有包含特定值val的节点移除。
解题思路:
草稿将求解过程演示一遍,思路清晰了很多。首先设置search扫描指针,负责从头到尾扫描链表。然后设置记录指针record,负责将移除节点后的链表连接起来。注意点是,当头节点同样包含特定值val,需要将head指针对应更新。
代码:
/**
* 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) {
if(head == NULL)
return head;
ListNode *search = head, *record = new ListNode(-999);
while(search != NULL)
{
if(search->val == val)
{
record->next = search->next;
if(head == search)
{
head = search->next;
}
}
else
{
record->next = search;
record = record->next;
}
search = search->next;
}
return head;
}
};
一遍AC啦~