203-Remove Linked List Elements

来源:互联网 发布:php javascript 区别 编辑:程序博客网 时间:2024/05/22 18:56

难度:easy
类别:linked list

1.题目描述

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

2.算法分析

遍历链表,比较head->next的值与val是否相等,如果相等的话,将其删除,并且head->next = head->next->next.
因为while循环中是head->next,所以最后要对第一节点进行判断。
整体思路很简单,实现也不难。

3.代码实现

ListNode* removeElements(ListNode* head, int val) {    if (head == NULL) return head;    if (head->next == NULL && head->val == val) return NULL;    if (head->next == NULL && head->val != val) return head;    ListNode* result = head;    ListNode* temp = NULL;    while (head->next != NULL) {        if (head->next->val == val) {            temp = head->next;            head->next = temp->next;            delete temp;        }        else {            head = head->next;        }    }    // 最后的时候再判断第一节点,看是不是需要删除    if (result->val == val) {        result = result->next;    }    return result;}