首页 > 其他分享 >leetcode-203-easy

leetcode-203-easy

时间:2022-10-23 12:22:57浏览次数:61  
标签:203 ListNode temp val head next easy return leetcode

Remove Linked List Elements

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.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

思路一: 递归,node 节点 == val, 递归调用 node.next

public ListNode removeElements(ListNode head, int val) {
    if (head == null) return head;

    if (head.val == val) {
        return removeElements(head.next, val);
    } else {
        head.next = removeElements(head.next, val);
        return head;
    }
}

思路二:迭代,创建一个头保存链表的引用,还有一个关键是用于遍历的 node,指向当前要判断 node

public ListNode removeElements(ListNode head, int val) {
    ListNode dummyHead = new ListNode(0);
    dummyHead.next = head;
    ListNode temp = dummyHead;
    while (temp.next != null) {
        if (temp.next.val == val) {
            temp.next = temp.next.next;
        } else {
            temp = temp.next;
        }
    }
    return dummyHead.next;
}

标签:203,ListNode,temp,val,head,next,easy,return,leetcode
From: https://www.cnblogs.com/iyiluo/p/16818326.html

相关文章

  • 数据结构 玩转数据结构 3-4 关于Leetcode的更多说明
    0课程地址https://coding.imooc.com/lesson/207.html#mid=13421 1重点关注1.1学习方法论1      自己花费了很多力气也解决不了的问......
  • 【重要】LeetCode 901. 股票价格跨度
    题目链接股票价格跨度注意事项使用单调栈代码classStockSpanner{public:StockSpanner(){this->stk.emplace(-1,INT_MAX);this->idx=-......
  • leetcode-283-easy
    MoveZeroes思路一:用left指针标记求解数组最大下标+1,初始化的时候是0,随着往右遍历,left会一步步扩大。最后把left右边的数都置为0。这题的关键在于left永远......
  • leetcode-231-easy
    PowerOfTwo思路一:观察2的n次方的二进制,都只有一位1bit,遍历即可publicbooleanisPowerOfTwo(intn){if(n<=0)returnfalse;intcount=0;......
  • LeetCode 1730. Shortest Path to Get Food
    原题链接在这里:https://leetcode.com/problems/shortest-path-to-get-food/题目:Youarestarvingandyouwanttoeatfoodasquicklyaspossible.Youwanttofind......
  • [LeetCode] 1768. Merge Strings Alternately
    Youaregiventwostrings word1 and word2.Mergethestringsbyaddinglettersinalternatingorder,startingwith word1.Ifastringislongerthantheot......
  • OpenEuler2203安装Redislabs的简单记录
    OpenEuler2203安装Redislabs的简单记录背景操作系统国产化的需求下想着都转型到openEuler上面来.应用和容器都没什么问题了,现在考虑一下一些企业软件最近一直在想研......
  • easyui文件限制格式
     文件后缀  easyui格式*.3gppaudio/3gpp,video/3gpp*.css text/css*.csv text/csv*.doc application/msword*.gif image/gif*.htm text/html*.html text/html*.jpeg......
  • 【leetcode_C++_哈希表_day5】242. 有效的字母异位词&&349. 两个数组的交集&&202.快乐
    C++知识补充:(不完全,仅针对本题用的知识点)1.C++类&对象关键字public确定了类成员的访问属性。在类对象作用域内,公共成员在类的外部是可访问的。您也可以指定类的成......
  • leetcode-169-easy
    MajorityElement思路一:mappublicintmajorityElement(int[]nums){if(nums.length==1)returnnums[0];Map<Integer,Integer>map=newHashMap<>(......