Remove Linked List Elements
2015.4.30 15:00
Remove all elements from a linked list of integers, that has value val.
Example
Given: 1---2--and 6---3---4---5, val = 6
Return: 1--2--and 3--4--5
Solution:
Watch out for boundary cases.
Accepted Code:
1 //1AC, no surprise2 /**3 * Definition for singly-linked list.4 * struct ListNode {5 * int val;6 * ListNode *next;7 * ListNode (int x): Val (x), Next (NULL) {}8 * };9 */Ten classSolution { One Public: Alistnode* removeelements (listnode* head,intval) { -ListNode *ptr; - the while(Head! = NULL && Head->val = =val) { -PTR =head; -Head = head->Next; - Deleteptr; + } - +ListNode *head0 =head; A at if(Head0 = =NULL) { - returnNULL; - } - - while(Head->next! =NULL) { - if(Head->next->val = =val) { inPTR = head->Next; -Head->next = ptr->Next; to Deleteptr; +}Else { -Head = head->Next; the } * } $ Panax Notoginseng returnhead0; - } the};
Leetcode-remove Linked List Elements