203. Remove Linked List Elements 206. Reverse Linked List java实现

博客记录了两道链表相关算法题,203题是移除链表中值为val的元素,作者认为自己写得不太好;206题是反转链表,用三指针解决。作者目标是每天做一道算法题,截至2019年5月31日已完成6道。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:203.Remove all elements from a linked list of integers that have value val.

	class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null) return head;
        while(head.val == val){
            head = head.next;
            if(head == null) return head;
        }
        ListNode cur = head;
        while(cur != null && cur.next != null){
            if(cur.next.val == val){
                cur.next = cur.next.next;
            }else{
                cur = cur.next;
            }
        }
        return head;
    }
}

本人写的,自我感觉写的不太好。看了几个java代码感觉都是大同小异,没有多大变化就不罗列了。


题目206. Reverse Linked List

这里是用三指针解决的,简单但复杂。

	class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode per = null;
        ListNode node = head;
        ListNode cur = head.next;
        
        while(true){
            node.next = per;
            per = node;
            node = cur;
            if(node == null)
                return per;
            cur = cur.next;
        }
    }
}

目标:每天一道算法题。
时间:2019-5-31
已完成:6道

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值