移除链表元素
题目描述
删除链表中等于给定值val的所有节点。
示例1
输入:1->2->4->3->2->5->2 val=2
输出:1->4->3->5
示例2
输入:1->1->1->1->4->5 val = 1
输出: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 top = new ListNode(0);
top.next = head;
ListNode pre = top;
ListNode temp = head;
while(temp!=null){
if(temp.val == val) pre.next = temp.next;
else pre = temp;
temp = temp.next;
}
return top.next;
}
}