for Robot Artificial Inteligence

22. Remove N-th Node From End of List

|

  • my solution
/**
 * 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) {
        if(!head)
            return nullptr;
        ListNode* p;
        ListNode* t;
        p = head;
        int size_ = 0;
        while(p)
        {
            size_++;
            p=p->next;
        }
        p = head;
        int i = 0;
        do
        {
            p = p->next;
            i++;
        }while(i <size_-n);
        t = p->next;
        *p = *t;
        delete t;
        return head;

    }
};
  • other solution
/**
 * 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* p = head;
        ListNode* q = head;
        int i = 0;
        while(q)
        {
            i++;
            q = q->next;
        }
        int j = 0;
        if(i==n) return head->next;
        while(j<i-n-1)
        {
            p= p->next;
            j++;
        }
        p->next = p->next->next;
        return head;

    }
};

Comments