203. Remove Linked List Elements
題目原文
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
解題思路
程式解答
class Solution
{
public:
ListNode* removeElements(ListNode* head, int val)
{
ListNode *p = new ListNode(0);
ListNode *ans = new ListNode(0);
p->next = head;
ans = p;
while (head)
{
if (head->val == val)
{
p->next = p->next->next;
}
else
{
p->next = head;
p = p->next;
}
head = head->next;
}
return ans->next;
}
};
Last updated
Was this helpful?