zoukankan      html  css  js  c++  java
  • LeetCode 19.删除链表的倒数第 n 个节点

    给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

    示例:

    给定一个链表: 1->2->3->4->5, 和 n = 2.
    
    当删除了倒数第二个节点后,链表变为 1->2->3->5.
    

    说明:

    给定的 n 保证是有效的。

    进阶:

    你能尝试使用一趟扫描实现吗?

    双指针法:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode fast = head;
            ListNode slow = head;
            for(int j = 0; j < n; j++) {
                fast = fast.next;
            }
            if(fast == null) { //如果删除的是第一个节点
                return head.next;
            }
            while(fast.next != null) {
                fast = fast.next;
                slow = slow.next;
            }
            slow.next = slow.next.next; //删除slow.next
            return head;
        }
    }
    
    如果博客内容有误,请联系我修改指正,非常感谢! 如果觉得这篇博客对你有用的话,就帮我点个小小的赞吧! 一起加油鸭, 越努力,越幸运!!!
  • 相关阅读:
    Sony Z1 USB 调试
    消除“Unfortunately, System UI has stopped”的方法
    变动数据模拟cons
    string to integer
    single number
    罗马数字转为阿拉伯数字
    整数逆序
    回文数字
    回文字符串
    count and say
  • 原文地址:https://www.cnblogs.com/studywithme/p/13552588.html
Copyright © 2011-2022 走看看