LeetCode #19

Remove Nth Node From End of List

1개의 풀이 · C++

문제 원문 보기 ↗

SOLUTION INFO

C++ · main.cpp

main.cpp
/**
 * 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) {
        ListNode *pre = head, *cur = head;
        for(int i = 0; i < n && cur; ++i) cur = cur->next;
        if(cur == nullptr) return pre->next;
        while(cur && cur->next) pre = pre->next, cur = cur->next;
        if(pre->next) pre->next = pre->next->next;
        else pre->next = nullptr;
        return head;
    }
};

SOLUTION DESCRIPTION

풀이 설명

등록된 풀이 설명이 없습니다.