Given the
head
of a linked list and an integerval
, remove all the nodes of the linked list that hasNode.val == val
, and return the new head.Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5]Example 2:
Input: head = [], val = 1 Output: []Example 3:
Input: head = [7,7,7,7], val = 7 Output: []Constraints:
- The number of nodes in the list is in the range
[0, 104]
.1 <= Node.val <= 50
0 <= val <= 50
今天leetcode的中文官网比较卡,所以是登录官网进行刷题的
移除链表元素这道题很简单,就是简单的对链表进行遍历,然后移除node.val = val的节点。
移除元素需要记录当前节点的前一个元素,然后直接将前一个元素的指针指向后一个元素就可以了,操作非常简单。为了保持链表中节点操作的一致,这里给head节点前增加了一个哑节点,后续的移除操作都可以使用pre.next = head.next;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
// 简单思路:直接遍历链表,移除node.val =val的节点
ListNode pre = new ListNode(-1);
pre.next = head;
ListNode start = pre;
ListNode next =null;
while(head != null) {
next = head.next;
if (head.val == val) {
pre.next = head.next;
head.next =null;
}else {
pre = pre.next;
}
head = next;
}
return start.next;
}
}
时间复杂度O(n)
空间复杂度O(1)
参考 哔哩哔哩 up主 爱学习的饲养员 刷题视频
手把手带你刷Leetcode力扣|各个击破数据结构和算法|大厂面试必备技能【已完结】-leetcode 203 移除链表元素
文章来源:https://www.toymoban.com/news/detail-627992.html
文章来源地址https://www.toymoban.com/news/detail-627992.html
到了这里,关于LeetCode 刷题 数据结构 链表 203 移除链表元素的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!