[leetcode]Remove Nth Node From End of List

/**
 * 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 *p = head;
        ListNode *result = new ListNode(-1);

        int i = 0;
        while (p != NULL)
        {
            i++;
            p = p->next;
        }
        if (i <= 1) return NULL;

        result->next = head;
        p = result;
        for (int j = 0;j < i - n; j++)
        {
            result = result->next;
        }

        result->next = result->next->next;

        return p->next;
    }
};

基础题

posted on 2015-10-23 16:08  Mereyct  阅读(174)  评论(0编辑  收藏  举报

导航