题目描述:(链接)
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
解题思路:
1 class Solution { 2 public: 3 ListNode* removeNthFromEnd(ListNode* head, int n) { 4 ListNode dummy(-1); 5 dummy.next = head; 6 ListNode *fast = &dummy; 7 ListNode *slow = &dummy; 8 9 for (int i = 0; i < n ; ++i) { 10 fast = fast->next; 11 } 12 13 while (fast->next != nullptr) { 14 slow = slow->next; 15 fast = fast->next; 16 } 17 18 // ListNode *tmp = slow->next; 19 slow->next = slow->next->next; 20 // delete tmp; 21 22 return dummy.next; 23 } 24 };