Leetcode 19 Remove Nth Node From End of List 链表
删除从后往前数的第n个节点
我的做法是将两个指针first,second
先将first指向第n-1个,然后让first和second一起指向他们的next,直到first->next->next为空
最后只要删除second->next
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeNthFromEnd(ListNode* head, int n) { 12 if(!head) return head; 13 14 ListNode* first = head; 15 for(int i = 0 ; i < n - 1; first = first->next, ++i); 16 17 if(!first->next){ 18 first = head; 19 head = head->next; 20 delete first; 21 return head; 22 } 23 24 ListNode* second= head; 25 for(;first->next->next; first = first->next, second = second->next); 26 27 ListNode* next = second->next; 28 second->next = next->next; 29 delete next; 30 31 return head; 32 } 33 };