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.

就是删除链表的倒数第n个结点

思路:最基本的快慢法,学过数据结构的应该都会

需要注意的一点是这道题的head指向的不是头结点,而是第一个结点,不知道后面的链表题是不是都是这样。。

ListNode* removeNthFromEnd(ListNode* head, int n) {
	ListNode* fast = head, *slow = new ListNode(0);//slow指向需删结点的前一结点
	slow->next = fast;
	head = slow;
	while (n--) 
		fast = fast->next;
	
	while (fast!=NULL) {
		slow = slow->next;
		fast = fast->next;
	}
	slow->next = slow->next->next;
	return head->next;
}