删除链表中等于给定值val
的所有节点。
给出链表 1->2->3->3->4->5->3
, 和 val = 3
, 你需要返回删除3之后的链表:1->2->4->5
。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/*
* @param head: a ListNode
* @param val: An integer
* @return: a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
// write your code here
if(head!=null)
{
while((head.val==val)&&(head!=null))
{
head=head.next;
if(head==null)
return null;
}
ListNode dummy = new ListNode(0);
dummy=head;
while(dummy.next!=null)
{
if(dummy.next.val==val)
{
dummy.next=dummy.next.next;
}
else dummy=dummy.next;
}
}
return head;
}
}