删除链表中等于给定值 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) {
//链表头为val的情况
while(head != null && head.val == val) head = head.next;
if(head == null) return head;
ListNode p = head;
while(p.next != null){
if(p.next.val == val){
p.next = p.next.next;
}else{
p = p.next;
}
}
return head;
}
}
/**
* 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 newHead = new ListNode(0);
newHead.next = head;
ListNode p = newHead;
//确保下一个元素存在
while(p.next != null){
if(p.next.val == val){
//下一个元素的val=val则删除该元素
p.next = p.next.next;
}else{
//下一个元素和val不相等,则p前进
p = p.next;
}
}
return newHead.next;
}
}