lintcode-Remove Linked List Elements-452

来源:互联网 发布:sdrsharp软件下载 编辑:程序博客网 时间:2024/06/05 20:59

Remove all elements from a linked list of integers that have value val.


样例

Given 1->2->3->3->4->5->3, val = 3, you should return the list as1->2->4->5

class Solution {  public:           ListNode *removeElements(ListNode *head, int val) {          if(!head)              return nullptr;          while(head&&head->val==val){            ListNode *p=head;            head=head->next;            free(p);        }              ListNode *ptr=head;          ListNode *q;          while(ptr){              if(ptr->val==val){                  if(!ptr->next){                      q->next=NULL;                      free(ptr);                  }else{                      ListNode *tmp=ptr->next;                      ptr->val=tmp->val;                      ptr->next=tmp->next;                      free(tmp);                  }                  }else{                  q=ptr;                  ptr=ptr->next;              }          }          return head;      }  }; 


0 0
原创粉丝点击