【Java】LeetCode题答-203移除链表元素
# LeetCood题目## !(https://gitee.com/gylq/cloudimages/raw/master/img/image-20210626190731545.png)
# 题答1(完整代码)
```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) {
while(head != null && head.val == val){
ListNode delNode = head;
head = head.next;
delNode.next = null;
}
if(head == null)
return head;
ListNode prev = head;
while(prev.next != null)
{
if(prev.next.val == val) {
ListNode delNode = prev.next;
prev.next = delNode.next;
delNode.next = null;
}
else
prev = prev.next;
}
return head;
}
}
```
# 题答2(利用虚拟头)
```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 Solution2 {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
if(head == null)
return head;
ListNode prev = dummyHead;
while(prev.next != null)
{
if(prev.next.val == val) {
ListNode delNode = prev.next;
prev.next = delNode.next;
delNode.next = null;
}
else
prev = prev.next;
}
return dummyHead.next;
}
```
# 本地测试截图
!(https://gitee.com/gylq/cloudimages/raw/master/img/image-20210626190930982.png)
页:
[1]