1 /**
2 * Definition of ListNode
3 * class ListNode {
4 * public:
5 * int val;
6 * ListNode *next;
7 * ListNode(int val) {
8 * this->val = val;
9 * this->next = NULL;
10 * }
11 * }
12 */
13 class Solution {
14 public:
15 /**
16 * @param head: The first node of linked list.
17 * @param n: An integer.
18 * @return: The head of linked list.
19 */
20 ListNode *removeNthFromEnd(ListNode *head, int n) {
21 // write your code here
22 if(n > 0) {
23 ListNode *pBegin=head, *pEnd=head;
24 while(n-- && pEnd!=NULL) {
25 pEnd = pEnd->next;
26 }
27 // n<链表长度
28 if(n == -1 && pEnd!=NULL) {
29 while(pEnd->next != NULL) {
30 pBegin = pBegin->next;
31 pEnd = pEnd->next;
32 }
33 pBegin->next = pBegin->next->next;
34 return head;
35 }
36 // n>链表长度
37 else if(n > -1 && pEnd!=NULL) {
38 return head;
39 }
40 // n=链表长度
41 else {
42 return head->next;
43 }
44 }
45 }
46 };