【LeetCode】203. Remove Linked List Elements 移除链表元素(Easy)(JAVA)
题目地址: https://leetcode.com/problems/remove-linked-list-elements/
题目描述:
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
题目大意
删除链表中等于给定值 val 的所有节点。
解题方法
- 遇到 head.val != val 的值就接到结果的链表里
- note: 接的时候要把链表后面断开
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode res = new ListNode();
ListNode pre = res;
while (head != null) {
ListNode next = head.next;
if (head.val != val) {
pre.next = head;
pre = head;
pre.next = null;
}
head = next;
}
return res.next;
}
}
执行耗时:1 ms,击败了99.65% 的Java用户
内存消耗:39.1 MB,击败了92.89% 的Java用户
![](https://img-blog.csdnimg.cn/20201107174624800.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE2OTI3ODUz,size_16,color_FFFFFF,t_70#pic_center)