Skip to content

19. Remove Nth Node From End of List

难度:Medium

刷题内容

原题连接

  • https://leetcode.com/problems/remove-nth-node-from-end-of-list/

内容描述

Given a linked list, remove the n-th 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.

˼· **- ʱ�临�Ӷ�: O(n)*- �ռ临�Ӷ�: O(1)***

ɾ内容描述n������Ϊ�˷�ֹ内容描述Ϊ1ʱ�Ŀ�ָ���쳣���Ȳ���һ������ͷ内容描述��ֻҪ�ȱ内容描述内容描述�����ܳ��ȣ������ܳ��ȼ�ȥ n 内容描述Ҫɾ内容描述ǰһ内容描述��ͷ�ij��ȣ�������ֻҪ�ø�ѭ���ҵ���ɾ��Ҫɾ���Ľڵ㼴�ɡ�

/**
 * 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) {
       ListNode* current = head;
        int num = 0;
        while(current)
        {
            num++;
            current = current ->next;
        }
        ListNode* n1 = new ListNode(0);
        n1 ->next = head;
        current = n1;
        num -= n;
        while(num)
        {
            num--;
            current = current ->next;
        }
        ListNode* temp = current ->next;
        current ->next = temp ->next;
        return n1 ->next;
    }
};

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组