struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { int num = 0; struct ListNode* p = head; struct ListNode* pre = NULL;//指向指针p前面的结点 while(p) //遍历指针求链表长度 { num++; p = p->next; } if(num < 1 || n == 0) { return head; } if(num == n) { return head->next; } p = head; int i = 1,x = num - n + 1;//记录要删除的结点(正数) while(p != NULL) { if(i == x) { break; } i++; pre = p; //指针p前面的结点 p = p->next; } pre->next = p->next;//删除要删除的结点 p->next = NULL; //工程规范,释放前把指针赋值为NULL free(p); //释放删除了的结点 p = pre->next; //p往后走,pre不动 return head; }