LeetCode OJ入门初探-203. Remove Linked List Elements

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) {
if(head == NULL)
{
return NULL;
}
while(head->val == val)
{
head = head->next;
if(head == NULL)
return NULL;
}
ListNode* one = head;
ListNode* two = head;
two = two->next;
while(two!=NULL)
{
if(two -> val == val)
{
one->next = two->next;
two = two->next;
}
else
{
one = two;
two = two->next;
}
}

return head;
}
};

发表评论