题目:
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.
提示:
此题可以通过双指针(两个指针之间相差n个间隔),这样可以保证一次遍历链表就完成题目中的要求。
有一些需要注意的地方:
- 被删去的节点记得要释放资源;
- 可以创建一个指向head的节点,然后初始状态下双指针均指向创建的这个节点,这样做可以让算法可以处理删除head节点的情况。
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { if (!head) return nullptr; ListNode new_head(-1); new_head.next = head; ListNode *slow = &new_head, *fast = &new_head; for (int i = 0; i < n; i++) fast = fast->next; while (fast->next) { fast = fast->next; slow = slow->next; } ListNode *to_be_deleted = slow->next; slow->next = slow->next->next; delete to_be_deleted; return new_head.next; } };