首页 > 其他 > 详细

LeetCode 19. 删除链表的倒数第N个节点

时间:2020-05-06 23:06:37      阅读:70      评论:0      收藏:0      [点我收藏+]
package 链表;

/**
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 * 19. 删除链表的倒数第N个节点
 * 思路:采用快慢指针,让快指针先走n步,慢指针从头开始,如果快指针的下一个节点为null,
 * 说明此时慢指针当前的节点就是要删除的节点,需要将慢指针指向下下个节点(跳过下一个节点)
 */
public class _19_Remove_Nth_Node_From_End_of_List {

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode fast = head;
            while (n-- > 0) {
                fast = fast.next;
            }
            if (fast == null) {
                return head.next;
            }
            ListNode slow = head;
            while (fast.next != null) {
                fast = fast.next;
                slow = slow.next;
            }
            slow.next = slow.next.next;
            return head;
        }
    }
}

LeetCode 19. 删除链表的倒数第N个节点

原文:https://www.cnblogs.com/jianzha/p/12838029.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!