leetcode203. 移除链表元素
方法一(删除头结点时另做考虑)
class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(head!=NULL && head->val==val) { head=head->next; } if(head==NULL) return NULL; //处理第一位是val的情况 while(head->val==val) { head=head->next; if(head==NULL) return NULL; } ListNode *curr=head->next; ListNode *pre=head; while(curr!=NULL) { if(curr->val==val) { pre->next=curr->next; } else pre=curr; curr=curr->next; } return head; } };
方法二(添加一个虚拟头结点)
class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* vir=new ListNode(-1); vir->next=head; ListNode *pre=vir; while(pre->next!=NULL) { if(pre->next->val==val) { pre->next=pre->next->next; } else pre=pre->next; } return vir->next; } };
方法三(递归)
class Solution { public ListNode removeElements(ListNode head, int val) { if(head==null) return null; head.next=removeElements(head.next,val); if(head.val==val){ return head.next; }else{ return head; } } }