栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

356-Leetcode 删除链表的倒数第N个节点

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

356-Leetcode 删除链表的倒数第N个节点


下面程序需要对如果删除的是第一个节点要进行判断,所以需要计算整个链表的长度

struct ListNode
{
	int val;
	ListNode* next;
	ListNode() : val(0), next(nullptr) {}
	ListNode(int x) : val(x), next(nullptr) {}
	ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution
{
public:
	int length(ListNode* head)
	{
		int count = 0;
		ListNode* first = head;
		while (first != nullptr)
		{
			++count;
			first = first->next;
		}
		return count;
	}
	ListNode* removeNthFromEnd(ListNode* head, int n)
	{
		ListNode* first = head;
		ListNode* second = head;
		int len = length(head);
		if (n == len)
		{
			ListNode* tmp = head;
			head = head->next;
			delete tmp;
			return head;
		}
		for (int i = 0; i < n; ++i)
		{
			second = second->next;
		}
		while (second->next)
		{
			first = first->next;
			second = second->next;
		}
		ListNode* tmp = first->next;
		first->next = tmp->next;
		delete tmp;
		return head;
	}
};
int main()
{
	Solution A;
	ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, nullptr))));
	ListNode* tmp = A.removeNthFromEnd(head, 2);
	return 0;
}

时间复杂度:O(L),其中 L 是链表的长度。
空间复杂度:O(1)
下面程序在头节点的前面又新增加了一个节点,这样就不用对头节点进行特殊的判断了

struct ListNode
{
	int val;
	ListNode* next;
	ListNode() : val(0), next(nullptr) {}
	ListNode(int x) : val(x), next(nullptr) {}
	ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution
{
public:
	ListNode* removeNthFromEnd(ListNode* head, int n)
	{
		ListNode* dummy = new ListNode(0, head);
		ListNode* first = head;
		ListNode* second = dummy;
		for (int i = 0; i < n; ++i) 
		{
			first = first->next;
		}
		while (first) 
		{
			first = first->next;
			second = second->next;
		}
		second->next = second->next->next;
		ListNode* ans = dummy->next;
		delete dummy;
		return ans;
	}
};
int main()
{
	Solution A;
	ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, nullptr))));
	ListNode* tmp = A.removeNthFromEnd(head, 2);
	return 0;
}

时间复杂度:O(L),其中 L 是链表的长度。
空间复杂度:O(1)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/879665.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号