题目来源:删除链表中的元素
题目描述:删除链表中等于给定值val的所有节点。
样例
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
Java代码:
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)
return head;
ListNode frist=head,last=head.next;
while (last!=null) {
if (last.val==val) {
frist.next=last.next;
last = frist.next;
}else {
frist = frist.next;
last = last.next;
}
}
if(head.val==val)
head = head.next;
return head;
}
}