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

相关推荐

牛客26538663...:感觉校园活动太多了,然后可能教育背景这种标题字号有点大
点赞 评论 收藏
分享
大愣子衰哥:老哥,是正式还是实习
点赞 评论 收藏
分享
05-23 19:33
重庆大学 Java
只学了传统后端,马上去后端实习了,在想要不要学习agent开发相关的。27秋招和26相比难度如何?
我连备胎都不是却还在...:就暑期实习而言,大厂官宣hc 比 26 多,但是我观察看应该低于 26 的,估计秋招也不简单
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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