LeetCode 203 Remove Linked List Elements

    xiaoxiao2021-03-25  11

    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

    AC代码如下:

    /** * 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) { while(head!=NULL&&head->val==val)//遍历到第一个节点值不等于val的节点 head=head->next; ListNode* ret=head;//返回指针 ListNode* p;//保存要删除节点的前一个节点指针 while(head!=NULL){ p=head; head=head->next; while(head!=NULL&&head->val==val) head=head->next; p->next=head; } return ret; } };

    转载请注明原文地址: https://ju.6miu.com/read-300359.html

    最新回复(0)