11ms C++ Solution


  • -1
    X
    class Solution {
    private:
        int getLength(ListNode *head) {
            int length = 0;
            while(head) {
                head = head->next;
                length++;
            }
            return length;
        }
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            if(n<1) return head;
            ListNode tempHead(0);
            ListNode* headptr = &tempHead;
            headptr->next = head;
            int index = getLength(head) - n;
            for(int i = 0; i < index; i++)
                headptr = headptr->next;
            ListNode* temp = headptr->next;
            headptr->next = headptr->next->next;
            delete temp;
            return tempHead.next;
        }
    };

  • 0
    C
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.