leetcode 203 移除链表元素
leetcode 203 移除链表元素
官网: https://leetcode-cn.com/problems/remove-linked-list-elements/
题目描述(中文)
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
题目描述(英文)
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
提交代码
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode removeElements(ListNode head, int val) { if(head == null) return null; ListNode node = removeElements(head.next, val); if(head.val == val){ head.next = null; return node; } else{ head.next = node; return head; } } }
提交反馈
执行结果:通过
执行用时 :2 ms, 在所有 Java 提交中击败了91.50%的用户
内存消耗 :39.4 MB, 在所有 Java 提交中击败了94.42%的用户