一、题目
二、代码
/**
* 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
{
//java用. 而且没有*
public ListNode removeElements(ListNode head, int val)
{
if(head==null) return null;
ListNode my_head= new ListNode(0);
ListNode process_node= new ListNode(0);
my_head.next= head;
process_node = my_head;
while(process_node.next != null)
{
if(process_node.next.val!= val)
{
//这一步一定是安全的
process_node = process_node.next;
}
else
{
//这一步不一定安全 所以还需要在外层判断
process_node.next = process_node.next.next;
}
}
return my_head.next;
}
}
三、运行结果
四、附录
二刷
/**
* 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)
{
head=head.next;
// System.out.println(" break ");
}
ListNode pro_node = new ListNode();
ListNode my_head = new ListNode();
pro_node.next = head;
my_head .next = head;
while(pro_node.next!=null)
{
while(pro_node.next.val == val)
{
if(pro_node.next.next == null)
{
pro_node.next =null;
break;
}
else
{
pro_node.next = pro_node.next.next;
}
}
if(pro_node.next ==null) break;
pro_node = pro_node.next;
}
// if(my_head.next !=null &&my_head.next.val == val) return null;
return my_head.next;
}
}