标签:
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeElements(ListNode* head, int val) { 12 if(head==NULL) return head; 13 ListNode* p,*q; 14 while(head->val==val) { 15 if(head->next==NULL){head=head->next;return head;} 16 head=head->next; 17 } 18 p=head,q=head->next; 19 while(q!=NULL){ 20 if(q->val==val) { 21 if(q->next==NULL) p->next=NULL; 22 p->next=q->next; 23 q=q->next;} 24 else {p=q; 25 q=q->next; 26 } 27 } 28 return head; 29 } 30 };
leetcode Remove Linked List Elements
标签:
原文地址:http://www.cnblogs.com/LUO77/p/5053110.html