【leetcode】19. Remove Nth From End of List(C)

本文介绍了一种算法,用于从链表中删除倒数第N个节点,并提供了详细的实现代码。通过计算链表长度并定位到待删除节点的前一个位置,实现了节点的高效移除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:

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

Example1:

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.
Note:
Given n will always be valid.

[ 题目链接 ]

提交代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) 
{
	if (head == NULL||head->next==NULL)
		return NULL;

	int i;
	int len=0,pos;
	struct ListNode* p = head;

	//calculate the len of the list
	while (p != NULL)
	{
		len++;
		p = p->next;
	}

	pos = len - n;
    p = head;
    if (pos == 0)
        return p->next;
	
	
	for (i = 0; i < pos-1; i++)
		p = p->next;

	struct ListNode* tmp = p->next;
	p->next = p->next->next;
	free(tmp);
	return head;
}

运行结果:
在这里插入图片描述

其他:
提交历史中有这个报错:
在这里插入图片描述
报错的代码行在这里:
在这里插入图片描述
报错的原因是刚开始我忘记加[p=head;]这句代码了,所以p的指向是混乱的,
所以我后面return p->next的时候,编译器就不知道我的p到底指向哪里。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值