Remove Linked List Elements

简介: Remove all elements from a linked list of integers that have value val. ExampleGiven: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6Return: 1 --> 2 --> 3 --> 4 --> 5 注意是不是头结点就ok了。

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

注意是不是头结点就ok了。

C++实现代码:

/**
 * 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 NULL;
        ListNode *p=head;
        ListNode *pre=head;
        while(p)
        {
            if(p->val==val)
            {
                if(p==head)
                {
                    head=p->next;
                    p->next=NULL;
                    delete p;
                    pre=head;
                    p=head;
                }
                else
                {
                    pre->next=p->next;
                    p->next=NULL;
                    delete p;
                    p=pre->next;
                }
            }
            else
            {
                pre=p;
                p=p->next;
            }
        }
        return head;
    }
};

 

目录
打赏
0
0
0
0
19
分享
相关文章
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
61 0
|
11月前
|
链表(Linked List)详解
链表(Linked List)详解
93 0
|
11月前
使用List中的remove方法遇到数组越界
使用List中的remove方法遇到数组越界
138 2
|
11月前
List中的remove方法遇到报错不能删除以及四种解决办法点赞收藏
List中的remove方法遇到报错不能删除以及四种解决办法点赞收藏
346 0
|
11月前
|
Java【问题记录 02】对象封装+固定排序+list All elements are null引起的异常处理+Missing artifact com.sun:tools:jar:1.8.0
Java【问题记录 02】对象封装+固定排序+list All elements are null引起的异常处理+Missing artifact com.sun:tools:jar:1.8.0
116 0
避免list中remove导致ConcurrentModificationException
避免list中remove导致ConcurrentModificationException
72 0
for-each或迭代器中调用List的remove方法会抛出ConcurrentModificationException的原因
for-each循环遍历的实质是迭代器,使用迭代器的remove方法前必须调用一下next()方法,并且调用一次next()方法后是不允许多次调用remove方法的,为什么呢?接下来一起来看吧
96 0
【PAT甲级 - C++题解】1133 Splitting A Linked List
【PAT甲级 - C++题解】1133 Splitting A Linked List
99 0
【PAT甲级 - C++题解】1074 Reversing Linked List
【PAT甲级 - C++题解】1074 Reversing Linked List
95 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等