Java 算法题笔记(八)

移除链表元素

删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

 法一:增加一个节点代替当前的头指针,这样如果头指针为应该跨过的指针,也可以用加的那个指针跨过。

public ListNode removeElements(ListNode head, int val) {
        ListNode header = new ListNode(-1);
        header.next = head;
        ListNode cur = header;
        while (cur.next != null){
            if (cur.next.val == val){
                // 这里判断cur.next != null 很好,可以使这句不会空指针异常
                cur.next = cur.next.next; // 这句是跨过节点
            }else {
                cur = cur.next; // 移动指针
            }
        }
        return header.next;
    }

 法二:

public ListNode removeElements(ListNode head, int val) {
        if (head == null) return null;
        ListNode cur = head,naxt = head.next;

        while (cur != null && naxt != null){
            if (cur.val == val){
                cur = cur.next;
                head = cur;
                naxt = cur.next;
                continue;
            }
            if (naxt.val == val){
                cur.next = naxt.next;
                naxt = cur.next;
                continue;
            }
            
            cur = cur.next;
            naxt = cur.next;
            
        }

        if (cur.val == val){
            return cur.next;
        }

        return head;
    }

二叉树的所有路径

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
List<String> result;
    public List<String> binaryTreePaths(TreeNode root) {
        result = new ArrayList<>();
        getPath(root,"");
        return result;
    }

    private void getPath(TreeNode root,String path){
        if (root == null) return;
        path = path + root.val;
        if (root.left != null)
            getPath(root.left,path+"->");
        if (root.right != null)
            getPath(root.right,path+"->");
        if (root.left == null && root.right == null)
            result.add(path);
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值