19. Remove Nth Node From End of List

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;
}
全部评论

相关推荐

10-28 10:48
已编辑
门头沟学院 Java
孩子我想要offer:发笔试后还没笔试把我挂了,然后邮箱一直让我测评没测,后面不知道干嘛又给我捞起来下轮笔试,做完测评笔试又挂了😅
点赞 评论 收藏
分享
11-04 22:56
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务