LeetCode 19. Remove Nth Node From End of List

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Follow up: Could you do this in one pass?

Example 1:

复制Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

Constraints:

The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

实现思路:

要剔除倒数第K个链表结点,于是可以进行统计链表总结点个数N,然后删除第N-K个结点即可。

AC代码:

class Solution {
	public:
		ListNode* removeNthFromEnd(ListNode* head, int n) {
			ListNode* temp=head;
			int allNum=0;//统计所有结点的个数
			while(temp!=NULL) {
				allNum++;
				temp=temp->next;
			}
			if(n>allNum) {
				return head;
			} else if(n==allNum) {
				head=head->next;
				return head;
			} else {
				int bgPos=allNum-n,cnt=0;//开始删除结点的位置
				temp=head;
				while(temp!=NULL) {
					cnt++;
					if(cnt==bgPos) {
						if(temp->next!=NULL) {
							temp->next=temp->next->next;
						} else temp->next=NULL;
						break;
					}
					temp=temp->next;
				}
			}
			return head;
		}
};
posted @   coderJ_ONE  阅读(36)  评论(0编辑  收藏  举报
编辑推荐:
· 电商平台中订单未支付过期如何实现自动关单?
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
· 大模型 Token 究竟是啥:图解大模型Token
阅读排行:
· 瞧瞧别人家的限流,那叫一个优雅!
· 1.net core 工作流WorkFlow流程(介绍)
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 面试官:如果某个业务量突然提升100倍QPS你会怎么做?
· .NET 平台上的开源模型训练与推理进展
点击右上角即可分享
微信分享提示