/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/***************************************************************************************
* 快慢双指针,left和right初始都指向链表头节点,right先走n步
* 如果移动n步后已达到最后一个节点,那么返回head->next节点
* 否则若right->next不为空,right向右移,且left也向右移,移动完成后left->next节点即为倒数第n个节点
*****************************************************************************************/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
int i;
struct ListNode *left = head;
struct ListNode *right = head;
if(head == NULL)
return head;
for(i = 0; i < n; i++)
right = right->next;
if(right == NULL)
return head->next;
while(right->next != NULL)
{
right = right->next;
left = left->next;
}
left->next = left->next->next;
return head;
}
};