0%

leetCode-203:Remove Linked List Elements

问题描述

给定一个链表和一个数字,要求删除链表中出现该数字的节点。题目链接:**点我**

样例输入输出

输入:[1,2,3,4,1,2,3] 3

输出:[1,2,4,1,2]

输入:[1,1] 1

输出:[]

问题解法

直接遍历遍历,删除匹配的节点即可。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 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)
{
ListNode dummy = new ListNode(-1, head);
ListNode p = dummy;
while (p.next != null)
{
if (p.next.val == val)
{
p.next = p.next.next;
}
else
{
p = p.next;
}
}

return dummy.next;
}
}