[LeetCode]203.Remove Linked List Elements

简介:

题目

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

思路

链表节点的删除操作。

代码

/*---------------------------------------
*   日期:2015-05-01
*   作者:SJF0115
*   题目: 203.Remove Linked List Elements
*   网址:https://leetcode.com/problems/remove-linked-list-elements/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
using namespace std;

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x),next(nullptr){}
};

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(head == nullptr){
            return nullptr;
        }//if
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        ListNode* pre = dummy;
        ListNode* cur = head;
        ListNode* tmp;
        while(cur){
            if(cur->val == val){
                tmp = cur;
                pre->next = cur->next;
                delete tmp;
                cur = pre->next;
            }//if
            else{
                pre = cur;
                cur = cur->next;
            }//else
        }//while
        return dummy->next;
    }
};

int main() {
    Solution solution;
    ListNode* head = new ListNode(1);
    ListNode* node1 = new ListNode(5);
    ListNode* node2 = new ListNode(2);
    ListNode* node3 = new ListNode(1);
    ListNode* node4 = new ListNode(4);
    ListNode* node5 = new ListNode(1);
    head->next = node1;
    node1->next = node2;
    node2->next = node3;
    node3->next = node4;
    node4->next = node5;

    head = solution.removeElements(head,6);
    while(head){
        cout<<head->val<<endl;
        head = head->next;
    }//while
}

运行时间
这里写图片描述

目录
相关文章
|
5月前
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
20 1
|
5月前
|
C++
Leetcode Copy List with Random Pointer(面试题推荐)
给大家推荐一道leetcode上的面试题,这道题的具体讲解在《剑指offer》的P149页有思路讲解,如果你手头有这本书,建议翻阅。
26 0
|
5月前
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
19 0
|
24天前
List中的remove方法遇到报错不能删除以及四种解决办法点赞收藏
List中的remove方法遇到报错不能删除以及四种解决办法点赞收藏
16 0
|
28天前
使用List中的remove方法遇到数组越界
使用List中的remove方法遇到数组越界
17 2
|
4月前
|
大数据 Java 程序员
「LeetCode合集」链表(List)及经典问题
「LeetCode合集」链表(List)及经典问题
27 0
|
5月前
避免list中remove导致ConcurrentModificationException
避免list中remove导致ConcurrentModificationException
20 0
|
10月前
for-each或迭代器中调用List的remove方法会抛出ConcurrentModificationException的原因
for-each循环遍历的实质是迭代器,使用迭代器的remove方法前必须调用一下next()方法,并且调用一次next()方法后是不允许多次调用remove方法的,为什么呢?接下来一起来看吧
55 0
List的remove操作一定要小心!
List的remove操作一定要小心!
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 141. 环形链表 Linked List Cycle

热门文章

最新文章