zoukankan      html  css  js  c++  java
  • 19. 删除链表的倒数第N个节点 双指针

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

    示例:

    给定一个链表: 1->2->3->4->5, 和 n = 2.

    当删除了倒数第二个节点后,链表变为 1->2->3->5.
    说明:

    给定的 n 保证是有效的。

    进阶:

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    快慢双指针
    其中当快指针第一趟走完已经为null时,直接返回head->next

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode() : val(0), next(nullptr) {}
     *     ListNode(int x) : val(x), next(nullptr) {}
     *     ListNode(int x, ListNode *next) : val(x), next(next) {}
     * };
     */
    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            if (!head | !head->next) {
                return nullptr;
            }
    
            ListNode* fast = head;
            ListNode* slow = head;
    
            for (int i = 0; i < n; i++) {
                fast = fast->next;
            }
            if (!fast) {
                return head->next;
            }
    
            while (fast->next) {
                fast = fast->next;
                slow = slow->next;
            }
    
            slow->next = slow->next->next;
    
            return head;
        }
    };
    
  • 相关阅读:
    iOS开发UI篇—字典转模型
    使用python编写批量卸载android应用的脚本
    CircularProgressBar
    Custom-Progress-Dialog-Android
    picasso jar
    swift
    Python编程
    H264分析工具
    Android Websites
    AnATools
  • 原文地址:https://www.cnblogs.com/xgbt/p/13833571.html
Copyright © 2011-2022 走看看