leetcode算法入门 第五天 双指针

876.链表的中间节点

先遍历一遍列表,记录列表的长度,得出中间列表的长度。

 public ListNode middleNode(ListNode head) {
        ListNode p = head;
        ListNode re = p;
        int i = 0;
        while(p != null){
            i++;
            p = p.next;
        }
        for(int j=1;j<=i/2;j++){
            re = re.next;
        }
        return re;
    }

也可以利用快慢指针,快指针一次走两步,慢指针一次走一步,判断条件只有当q不为空且q.next不为空才有继续往下走的必要。

 public ListNode middleNode(ListNode head) {
        ListNode p = head, q = head;
        while (q != null && q.next != null) {
            q = q.next.next;
            p = p.next;
        }
        return p;
    }

19.删除链表的倒数N个元素

public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head;
        ListNode low = fast;
        ListNode re = low;
        for(int i=1; i<=n; i++){
            fast = fast.next;
        }
        if(fast == null){
            re = re.next;
            return re;
        }
        while(fast.next != null){
            fast = fast.next;
            low = low.next;
        }
        low.next=low.next.next;
        return re;

    }

也可以利用递归方法

int count = 0;
public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null){
            return null;
        }
        head.next = removeNthFromEnd(head.next,n);
        count++;
        if(count == n){
            return head.next;
        }
        return head;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值