题目: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个结点,要求一次遍历完成。利用双指针pre和cur遍历,让cur先遍历n个结点,如果cur为空,那么删除的就是链表的头结点,直接返回头结点的下一个位置即可,否则cur和pre同时遍历直到cur指向链表的最后一个元素,此时pre所指的结点是将要删除结点的前驱结点,执行pre->next = pre->next->next即可删除指定的结点。代码如下:
/**
* 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->next) return NULL;
ListNode *pre = head, *cur = head;
for (int i = 0; i < n; ++i) cur = cur->next;
if (!cur) return head->next;
while (cur->next) {
cur = cur->next;
pre = pre->next;
}
pre->next = pre->next->next;
return head;
}
};