`

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

从链表中删除节点为给定值得所有节点。对于在链表中删除节点的问题,如果头结点可能被删除的情况下,我们往往创建一个helper节点,让它指向头结点。这样从helper节点的next开始处理,最后返回help.next就可以了。代码如下:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode helper = new ListNode(0);
        helper.next = head;
        head = helper;
        while(head.next != null) {
            if(head.next.val == val) {
                head.next = head.next.next;
            } else {
                head = head.next;
            }
        }
        return helper.next;
    }
}
分享到:
评论

相关推荐

    python-leetcode题解之203-Remove-Linked-List-Elements.py

    Python-leetcode题解之203-Remove-Linked-List-Elements.py 在解决LeetCode上的“Remove Linked List Elements”问题时,我们面对的是一个常见的数据结构问题,即如何在单链表中移除特定元素。该问题要求我们编写一...

    leetcode2sumc-LeetCode:LeetCode的一些题目

    leetcode 2 sum c LeetCode 帮助文档 帮助文档存放在Help文件夹下。 文件名 文件描述 ...complexitypython.txt Python的一些常规操作的...Elements no 206 Easy Reverse Linked List 234 Easy Palindrome Linked List

    Leetcode部分试题解析

    27. **Remove Linked List Elements**:移除链表中的特定元素。可以使用迭代方法,同时保持指向下一个非目标节点的引用。 28. **Remove Element**:从数组中移除特定元素。双指针法可以有效地完成这个任务。 29. *...

    leetcode跳跃-LeetCode:力扣刷题70道!

    Elements 力扣 206 反转链表 | Reverse Linked List 队列 Queue 力扣 933 最近的请求次数 | Number of Recent Calls 力扣 225 用队列实现栈 | Implement Stack Using Queue 力扣 622 设计循环队列 | Design ...

    LeetCode最全代码

    * [Linked List](https://github.com/kamyu104/LeetCode#linked-list) * [Stack](https://github.com/kamyu104/LeetCode#stack) * [Queue](https://github.com/kamyu104/LeetCode#queue) * [Heap]...

    List实现 数据结构 模板

    class DoublyLinkedList { private: Node* head; public: DoublyLinkedList(); ~DoublyLinkedList(); // 添加其他成员函数,如:add、remove、get、set等 }; ``` 以上三种实现各有优缺点。数组实现适合于需要...

    双向链表 链表(C++编写)

    Our doubly linked lists have two header elements: the "head" just before the first element and the "tail" just after the last element. The `prev' link of the front header is null, as is the `next' ...

    leetcod 203.移除链表元素:

    (题目来源:https://leetcode.cn/problems/remove-linked-list-elements/description/) 解题思路有两种:(一)要移除链表中值为val的节点,我们肯定是要将链表遍历一遍的,关键是我们在遍历中如何操作是一个问题...

    队列实现火车厢重排的算法及代码(个人创作)

    // Node structure for linked list struct Node { int data; Node* next; }; // Linked Queue class class LinkQueue { private: Node* first, *rear; public: LinkQueue(); // Constructor ~LinkQueue(); /...

Global site tag (gtag.js) - Google Analytics