Remove Nth node from End of list--LeetCode

本文介绍了一种高效算法,用于删除单链表中倒数第N个节点,仅通过一次遍历实现。该方法利用双指针技巧,确保了操作的简洁性和性能的优化。

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

题目:

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

For 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.

Note:
Given n will always be valid.
Try to do this in one pass.


思路:

建立两个相隔n的指针,两个指针同时向外遍历。当后一个指针到链表末尾时,删除第一个指针对应的节点。不过为了更加方便的删除 是的第一个节点指向被删除节点的前一个节点最好
#include <iostream>
#include <vector> 
using namespace std;
/*
 Given a linked list, remove the nth node from the end of list and return its head.

For 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.

Note:
Given n will always be valid.
Try to do this in one pass.
*/
/*
删除链表的倒数第n个节点 
使用两个指针来开始遍历 中间间隙可以为n,等到后一个节点达到末尾,删除前面的那个节点 
假如我们需要删除第N个节点,那么是的first和second之间的距离为n,等到 second的节点为Null,
那么我们就删除first->next节点即可 
*/

typedef struct list_node List;
struct list_node
{
	struct list_node* next;
	int value;
};

void print_list(List* list)
{
	List* tmp=list;
	while(tmp != NULL)
	{
		cout<<tmp->value<<endl;
		tmp = tmp->next; 
	}
}

/*
初始化List  将从1~n的数字插入到链表中 
*/
void Init_List(List*& head,int n)
{
	head = NULL;
	List* tmp;
	List* record;
	/*
	for(int i=1;i<=n;i++)
	{
		tmp = new List;
		tmp->next = head;
		tmp->value = i;
		head = tmp;
 
	}
	*/
	for(int i=1;i<=n;i++)
	{
		tmp = new List;
		tmp->next = NULL;
		tmp->value = i;
		if(head == NULL)
		{
			head = tmp;
			record = head;
		}
		else
		{
			record->next = tmp;
			record = tmp;
		}
	}
}

int Len_list(List* list)
{
	if(list == NULL)
		return 0;
	else
		return Len_list(list->next)+1;
}


void Remove_nth(List*&list ,int nth)
{
	List* first;
	List* second;
	int i;
	first = second = list;
	for(i=1;i<=nth && second !=NULL;i++)
		second = second->next;
	 
	while(second != NULL && second->next != NULL)
	{
		first = first->next;
		second = second->next;
	}
 
	if(first == list)
	{
		
		list = first->next;
		delete first;
	}
	else
	{
		second = first->next;
		first->next = second->next;
		delete second;	
	}
	
}

int main()
{
	List* head;
	Init_List(head,10);
	Remove_nth(head,3);
	
	print_list(head);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值