资讯专栏INFORMATION COLUMN

leetcode 19 Remove Nth Node From End of List

chaosx110 / 2918人阅读

摘要:题目详情题目要求输入一个和一个数字。要求我们返回删掉了倒数第个节点的链表。想法求倒数第个节点,我们将这个问题转化一下。我们声明两个指针和,让和指向的节点距离差保持为。解法使点和点的差距为同时移动和使得到达的末尾删除倒数第个节点

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

题目要求输入一个linked list 和一个数字n。要求我们返回删掉了倒数第n个节点的链表。

For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.

想法

求倒数第n个节点,我们将这个问题转化一下。

我们声明两个指针low和fast,让fast和low指向的节点距离差保持为n。

这样当fast指向了链表中的最后一个节点时,low指针指向的节点就是我们所求的倒数第n个节点了。

解法
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode start = new ListNode(0);
        
        ListNode slow = start , fast = start;
        slow.next = head;
        
        //使fast点和slow点的差距为n
        for(int i=1;i<=n+1;i++){
            fast = fast.next;
        }
        
        //同时移动fast和slow 使得fast到达listnode的末尾
        while(fast != null){
            slow = slow.next;
            fast = fast.next;
        }
        
        //删除倒数第n个节点
        slow.next = slow.next.next;      
        
        return start.next;
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68762.html

相关文章

  • leetcode19 Remove Nth Node From End of List 从链表中移除

    摘要:虽然时间复杂度还是但是显然我们可以再一次遍历中完成这个任务。现在跳出下标的思路,从另一个角度分析。快慢节点之间的距离始终是。当快节点到达终点时,此时的慢节点就是所要删去的节点。 题目要求 Given a linked list, remove the nth node from the end of list and return its head. For example, ...

    YPHP 评论0 收藏0
  • leetcode 19. Remove Nth Node From End of List

    摘要:这题也是携程年暑假实习生的笔试题。最开始想的解法就是,先循环求链表的长度,再用长度,再循环一次就能移除该结点。结果对的,但是超时了。再返回整个链表。 Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2...

    bigdevil_s 评论0 收藏0
  • leetcode-019-删除链表倒数第N个结点(Remove Nth Node From End

    摘要:第题给定一个链表,删除链表的倒数第个节点,并且返回链表的头结点。因为,若有一个真正的头结点,则所有的元素处理方式都一样。但以第一个有效元素为头结点,就导致算法的不一致,需要单独处理第一个有效元素头结点。 leetcode第19题 Given a linked list, remove the n-th node from the end of list and return its h...

    brianway 评论0 收藏0
  • LeetCode 19:删除链表的倒数第N个节点 Remove Nth Node From End

    摘要:给定一个链表,删除链表的倒数第个节点,并且返回链表的头结点。示例给定一个链表和当删除了倒数第二个节点后,链表变为说明给定的保证是有效的。值得注意的的是,指向应当删除的节点并无法删除它,应当指向该删除节点的前一个节点。 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 Given a linked list, remove the n-th node from the ...

    qiangdada 评论0 收藏0
  • LeetCode 19:删除链表的倒数第N个节点 Remove Nth Node From End

    摘要:给定一个链表,删除链表的倒数第个节点,并且返回链表的头结点。示例给定一个链表和当删除了倒数第二个节点后,链表变为说明给定的保证是有效的。值得注意的的是,指向应当删除的节点并无法删除它,应当指向该删除节点的前一个节点。 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 Given a linked list, remove the n-th node from the ...

    周国辉 评论0 收藏0

发表评论

0条评论

chaosx110

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<