chenzhuantou

题目:移除链表元素

描述:
删除链表中等于给定值 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;

    }
}

相关文章:

  • 2021-07-31
  • 2021-02-03
  • 2021-10-16
  • 2021-10-16
  • 2021-12-26
  • 2020-12-23
  • 2021-12-26
  • 2021-11-11
猜你喜欢
  • 2020-12-31
  • 2021-09-07
  • 2020-04-11
  • 2019-01-24
  • 2021-12-06
  • 2021-12-26
  • 2020-06-20
相关资源
相似解决方案