题目描述
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
解法
使用哑结点,只需要变更next指针即可。
/**
* 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 ya = new ListNode(0);
ListNode cur = head, ret=ya;
while(cur !=null) {
if(cur.val != val) {
ya.next = cur;
ya = ya.next;
}
cur = cur.next;
}
ya.next=null;
return ret.next;
}
}