LeetCode题目地址
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-linked-list-elements/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
解答
方法1:
/**
* @auther jintao.zhang
* @date 2020-1-6 10:58
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode removeElements(ListNode head, int val) {
//如果是头结点需要删除,或者头结点的下一个节点,也为待删除的节点,因此此处需要使用while循环,直到头结点不为待删除的节点
while (head != null && head.val == val){
ListNode ret = head;
head = head.next;
ret.next = null;
}
//如果经过上述步骤后,整个链表为空了,此时直接返回head节点
if (head