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.
思路:快慢指针。注意代码鲁棒性。时间复杂度O(n),空间复杂度O(1)
相关题目:《剑指offer》面试题15
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 == NULL || n <= 0) return head; 13 ListNode *pfast = head; 14 for (int i = 1; i < n; ++i) { 15 if (pfast == NULL) break; //这是为了k的值大于链表节点总数的情况,本题不存在这种情况 16 pfast = pfast->next; 17 } 18 ListNode **pslow = &head; 19 while (pfast->next != NULL) { 20 pfast = pfast->next; 21 pslow = &((*pslow)->next); 22 } 23 24 ListNode *q = *pslow; 25 *pslow = q->next; 26 delete q; 27 28 return head; 29 } 30 };