删除链表中等于给定值 val 的所有节点。
输入: 1->2->6->3->4->5->6, val = 6
输出: 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) {
ListNode pre = new ListNode();
pre.next = head;
ListNode curral = pre;
while (curral.next != null){
if (curral.next.val == val){
curral.next = curral.next.next;
}else{
curral = curral.next;
}
}
return pre.next;
}
}
解法二:分情况进行删除。先删除头节点,后删除非头节点
```java
/**
* 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) {
//先删除头节点
ListNode newNode = new ListNode();
newNode = head;
//注意这里是while而不能是if;
while (head != null && head.val == val){
head = head.next;
newNode = head;
}
while (head != null && head.next != null){
if (head.next.val == val){
head.next = head.next.next;
}else{
head = head.next;
}
}
return newNode;
}
}