题目:移除链表元素
描述:
删除链表中等于给定值 val 的所有节点。
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
预备知识:
思路:
1、判断空指针
2、增加虚拟头指针(知识点):预防head为一个值的情况,增加代码编写难度
3、使用while循环判断val值
Oj:
https://leetcode-cn.com/problems/remove-linked-list-elements/
代码:
/**
*题目:删除链表中等于给定值 val 的所有节点。(203)
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
*思路:
* 1、判断空指针
* 2、增加虚拟头指针(知识点)
* 3、使用while循环判断val值
*/
class Solution {
class ListNode {
int val;
ListNode next;//成员变量成员变量成员变量成员变量成员变量成员变量成员变量
ListNode(int x) { val = x; }
}
public ListNode removeElements(ListNode head, int val) {
//判空
if (head == null){
return head;
}
//虚拟头结点
ListNode Vhead = new ListNode(0);
Vhead.next = head;
ListNode cur = Vhead;
//寻找目标值
while (cur.next != null){
if (cur.next.val == val){
ListNode deNode = cur.next;
cur.next = deNode.next;
}else {
cur = cur.next;
}
}
return Vhead.next;
}
}