[Leetcode] Remove Nth Node From End of List

Remove Nth Node From End of List 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/


Description

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

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.

Solution


class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *frontNode = head, *backNode = head;
        int i = 0;
        while (backNode -> next != NULL && i < n) {
            backNode = backNode -> next;
            i++;
        }
        if (backNode -> next == NULL && i < n) {
            frontNode = head -> next;
            delete head;
            return frontNode;
        }
        while (backNode -> next != NULL) {
            frontNode = frontNode -> next;
            backNode = backNode -> next;
        }
        ListNode* temp = frontNode -> next;
        frontNode -> next = temp -> next;
        delete temp;
        return head;
    }
};


解题描述

这道题题意是删除给出链表的倒数第n个节点。主要的问题在于:

  1. 只用一趟扫描链表完成
  2. 判断n是否大于链表长度

这里的解法主要的思想是链表问题中常用的前后双指针:设置2个指针,步长相差n个节点,同时向后进行移动,当后一个指针到达链表尾的时候,前一个指针就刚好落在要删除的节点上。

原文地址:https://www.cnblogs.com/yanhewu/p/8350398.html