[leetcodeブラシシリーズ]Remove Nth Node From End of List

1926 ワード

模擬問題、何も言うことはありません.ポインタの操作がもう熟練していないような気がします.まだ練習が必要です.
/**
 * 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
        if(head == 0)
            return 0;
        int len = 1;
        ListNode* p = head;
        while(p->next != 0)
            len ++ ,p = p->next;
        if(len == n)
            return head->next;
        int now = 1;
        p = head;
        while(p->next != 0){
            ++ now;
            if(now == len - n + 1){
                p->next = p->next->next;
                return head;
            }
            p = p->next;
        }
    }
};

====以下は8月7日午前更新====
昨夜cc 150を見て、two pointer操作でチェーンタイプの問題を解決する方法を話したので、今日はこの問題を持って練習してみましょう.
/**
 * 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
        if(head == 0 || n <= 0)
            return head;
        ListNode* p1 = head;
        ListNode* p2 = head;
        for(int i = 0; i < n - 1; ++ i)
            if(p2->next != 0)
                p2 = p2->next;
            else
                return head; // length < n
        if(p2->next == 0) // length == n 
            return head->next;
        p2 = p2->next;
        while(p2->next != 0)
            p1 = p1->next, p2 = p2->next;
        p1->next = p1->next->next;
        return head;
    }
};