题目地址
https://leetcode.com/problems/remove-linked-list-elements/description/
题目描述
203. 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与所给val相等, 则跳过.
关键点
- 注意, 此题一开始要把head往前走一位, 因为要看下head是不是需要删除.
代码
- 语言支持:Java
/**
* 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) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
while (head.next != null) {
if (head.next.val == val) {
head.next = head.next.next;
} else {
head = head.next;
}
}
return dummy.next;
}
}
网友评论