题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
这种倒数第n个节点的不出意外都是用双指针,这道题就是简单的删除。
```/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
if(!head) return head;
ListNode* fast = head;
ListNode* slow = head;
for(int i = 0;i<n &&head;i++)
{
fast = fast->next;
}
if(!fast)
return head->next;
while(fast->next){
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return head;
}
};