删除链表中等于给定值 val 的所有节点. 这题粗看并不困难,链表的特性让移除元素特别轻松,只用遇到和val相同的就跳过,将指针指向下一个,以此类推. 但是,一个比较麻烦的问题是,当链表所有元素都和val相同时,如果直接使用参数给的head,则返回的一定会保留第一位的节点,而题意是要返回空值. 对上述情况使用特判又会与“第一个节点的值和val不同,第二个节点之后和val值相同”相矛盾. 所以想到的思路是,新建一个节点,将这个节点接在head的最前面,保证第一个节点无意义,这样,哪怕遇到上述情况,…
203. 移除链表元素 删除链表中等于给定值 val 的所有节点. 示例: 输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ cla…
题目 203. 移除链表元素 删除链表中等于给定值 val 的所有节点. 题解 删除结点:要注意虚拟头节点. 代码 class Solution { public ListNode removeElements(ListNode head, int val) { ListNode pre= new ListNode(-1); pre.next=head; ListNode cur = pre; while(cur.next!=null){ if(cur.next.val==val){//每次判断…
203.移除链表元素 知识点:链表:双指针 题目描述 给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 . 示例 输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5] 输入:head = [], val = 1 输出:[] 输入:head = [7,7,7,7], val = 7 输出:[] 解法一:迭代法 思路是很简单的,就是遍历链表,当遇到与val值相等的时候…
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 Credits:Special thanks to @mithmatt for adding this probl…
/* * @lc app=leetcode.cn id=203 lang=c * * [203] 移除链表元素 * * https://leetcode-cn.com/problems/remove-linked-list-elements/description/ * * algorithms * Easy (39.58%) * Total Accepted: 18.3K * Total Submissions: 46.2K * Testcase Example: '[1,2,6,3,4,5,…
Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given…
Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given…
本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是LeetCode专题的第51篇文章,我们来看LeetCode第82题,删除有序链表中的重复元素II(Remove Duplicates from Sorted List II). 这题官方给出的难度是Medium,点赞1636,反对107,通过率在36.3%左右.根据我们之前的分析,这题的难度适中,并且质量很高,好评如潮.实际上也的确如此,这题算法本身并不难,但是想要完整没有bug地实现并不容易,我们一起来看看. 题意 给定一个有…
Easy! 题目描述: 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次. 示例 1: 输入: 1->1->2 输出: 1->2 示例 2: 输入: 1->1->2->3->3 输出: 1->2->3 解题思路: 移除有序链表中的重复项需要定义个指针指向该链表的第一个元素,然后第一个元素和第二个元素比较,如果重复了,则删掉第二个元素,如果不重复,指针指向第二个元素.这样遍历完整个链表,则剩下的元素没有重复项. C++解法一: /** * D…