[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; } };
基础题