Fork me on GitHub

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

题目

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. 

解析

  • 两种思路
  • 思路一:第一遍遍历得到链表的长度,第二遍走cnt-n步,注意边界条件
  • 思路二:两个指针,第一个先走n-1步,然后两个指针一起走

// 19. Remove Nth Node From End of List
class Solution {
public:
	ListNode* removeNthFromEnd(ListNode* head, int n) {

		ListNode* cur = head;
		if (head==NULL)
		{
			return NULL;
		}
		int cnt = 0;
		while (cur!=NULL)
		{
			cnt++;
			cur = cur->next;
		}
		cur = head;
		int pos = cnt - n+1;
		if (pos==1)
		{
			return cur->next;
		}
		pos = pos - 2;
		while (pos)
		{
			cur = cur->next;
			pos--;
		}
		ListNode* dete = cur->next;
		if (dete->next)
		{
			cur->next = cur->next->next;
		}
		else
		{
			cur->next = NULL;
		}
		
		
		//delete dete;
		return head;
	}
};

题目来源

posted @   ranjiewen  阅读(148)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 开发者新选择:用DeepSeek实现Cursor级智能编程的免费方案
· Tinyfox 发生重大改版
· 独立开发经验谈:如何通过 Docker 让潜在客户快速体验你的系统
· 小米CR6606,CR6608,CR6609 启用SSH和刷入OpenWRT 23.05.5
· 近期最值得关注的AI技术报告与Agent综述!
点击右上角即可分享
微信分享提示