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的情况。
/**
* 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 == nullptr)
return head;
ListNode *p = head;
while(p->next != nullptr)
{
if(p->next->val == val)
p->next = p->next->next;
else
p = p->next;
}
if(head->val == val)
head = head->next;
return head;
}
};