leetcode203. Remove Linked List Elements

来源:互联网 发布:网络主播套路 编辑:程序博客网 时间:2024/06/06 06:37

删除链表的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==NULL)return head;        ListNode* p=head;        ListNode* q=p->next;        while(q!=NULL){            // cout<<q->val<<endl;            if(q->val==val){                p->next=q->next;                 q=q->next;            }            else{                q=q->next;                p=p->next;            }               }        if(head->val==val) return head->next;        else return head;        return head;            }};