203. Remove Linked List Elements

来源:互联网 发布:淘宝冻结账户开通 编辑:程序博客网 时间:2024/05/21 21:48

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

删除整数链表中所有值为val 的元素

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val  = 6

Return: 1 --> 2 --> 3 --> 4 --> 5


删除节点分两种情况:如果待删除元素是头结点,则head指针要后移,如果是中间节点,则正常删除单链表节点。

所以使用两个while循环,先进行处理头结点,再处理中间节点,遍历一次链表即可完成删除操作。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* removeElements(struct ListNode* head, int val) {    struct ListNode *p,*q;    while(head!=NULL&&head->val==val)       //删除头结点    {        p=head;        head=head->next;        free(p);    }    if(head!=NULL)                          //删除中间节点    {        p=head;        while(p->next!=NULL)        {           if(p->next->val==val)           {               q=p->next;               p->next=p->next->next;               free(q);           }           else           p=p->next;            }    }    return head;}



0 0
原创粉丝点击