LeetCode | 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->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

思路:

建立两个相隔n的指针,两个指针同时向外遍历。当后一个指针到链表末尾时,删除第一个指针对应的节点。

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode * begin  = head;
        ListNode * first = head;
        ListNode * second = head;
        
        for(int i = 0; i < n; i++)
        {
            second = second->next;
        }
        
        if(second == NULL)
        {
            begin = begin->next;
        }
        else
        {
            while(second->next != NULL)
            {
                first = first->next;
                second = second->next;
            };
            
            first->next = first->next->next;
        }
        
        return begin;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11695011
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞