1 //使用两次遍历 2 ListNode* removeNthFromEnd(ListNode* head, int n) { 3 if (!head->next) return NULL; 4 int len = 0; 5 ListNode *p = head; 6 while (p) { 7 p = p->next; 8 ++len; 9 } 10 11 p = head; 12 if (len == n) 13 return head->next; 14 for (int j = 0; j < len - n -1; ++j) {//因为头结点存在 15 p = p->next; 16 } 17 18 p->next = p->next->next; 19 return head; 20 } 21 22 //使用单次遍历,先使p移动n+1个位子,即剩下还有(len-n-1)个位子,对应面上面的j循环 23 //然后将q从头移动,并同时p向后移动,从而可知q的位置就是倒数第n个位置 24 ListNode* removeNthFromEnd(ListNode* head, int n) { 25 if (!head->next) return NULL; 26 ListNode *p = head; 27 for (int i = 0; i < n; ++i)p = p->next; 28 if (!p)return head->next; 29 ListNode *q = head; 30 while (p->next) { 31 p = p->next; 32 q = q->next; 33 } 34 q->next = q->next->next; 35 return head; 36 }