首页 > 代码库 > 删除链表中的指定元素节点

删除链表中的指定元素节点

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

Have you met this question in a real interview? 
Yes
Example

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

要注意开始的节点是否是要删除节点,还有中间有连续的待删除节点,和最后的节点需要删除情况

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * @param head a ListNode
     * @param val an integer
     * @return a ListNode
     */
    ListNode *removeElements(ListNode *head, int val) {
        // Write your code here
        if(head == NULL )return NULL;
        while(head != NULL && head->val == val)
        {
            head = head->next;
        }
        if(head == NULL )return NULL;
        ListNode *p = head;
        while(p->next != NULL)
        {
            if(p->next->val != val)
            p = p->next;
            else
            {
                ListNode *tmp = p->next;
                while(tmp != NULL && tmp->val == val)
                {
                    tmp = tmp->next;
                }
                p->next = tmp;
                p = p->next;
            }
            if(p == NULL)break;
        }
        return head;
        
    }
};

 

删除链表中的指定元素节点