题目描述
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
样例
1->2->3->4->5
n = 2
输出 1->2->3->5
C++ 代码
/**
* 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) {
ListNode *dummy = new ListNode(-1); // 首先新建一个链表的结点
dummy->next = head; //令这个结点指向head
ListNode *first = dummy, *second = dummy; //同时设置双指针指向该节点
for (int i = 0; i < n; i ++ ) //将first指针指向第n个数 second 指针不动,还是在最前面,此时first //和second这个节点相差n
{
first = first->next;
}
//当first结点指向最后的空d结点时second结点刚好指向倒数第n个结点
while (first -> next)
{
first = first->next;
second = second->next;
}
//直接删掉这个倒数第n个结点
second->next = second->next->next;
return dummy->next;
}
};