1.1数组和链表:19. Remove Nth Node From End of List(Leetcode)

Given a linked list, remove the nth node from the end of list and return its head.

题目大意:

给定一个链表,删除它倒数第n位的节点并重新返回此链表

博主想到的方法比较简单,先遍历一次求出链表的长度,确定是正数第几个节点被删除,然后二次遍历删除它

方法一:

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
int length = 0; ListNode first = head; while(head != null){ length ++; head = head.next; } int index = length - n + 1; if(index == 1) return first.next; int count = 0; ListNode result = first; while(true){ count ++; if(index == count + 1){ first.next = first.next.next; return result; } first = first.next; } }}


网上介绍了另外一种方法比较直观,使用了双指针思想,但就运行速度来说都是O(n)

方法二:

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int diff = 0;
        ListNode p1 = head;
        while(diff <= n){
            p1 = p1.next;
            if(p1 == null ){
                if(n == diff){
                    head.next = head.next.next;
                    return head;
                }else
                    return head.next;
            }
                
            diff++;
        }
        ListNode p2 = head;
        while(p1 != null){
            p1 = p1.next;
            p2 = p2.next;
        }
        p2.next = p2.next.next;
        return head;
    
    }
}
定义两个指针相差n个节点,当p1指针指向末尾指针下一个时(null),删除p2节点下一个节点




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值