LeetCode C++17-删除链表的倒数第N个结点

题目描述

        给你一个链表,删除链表的倒数第n个结点,并返回链表的头结点。

举例

示例1: 输入: head=[1,2,3,4,5], n=2   输出:[1,2,3,5]

示例2: 输入: head=[1], n=1    输出: []

示例3: 输入: head=[1,2], n=1  输出: [1]

解题方法: 快慢指针+哨兵节点。始终保持fast指针跟slow指针的距离为n+1,当fast指针到最后一个节点的下一个节点(即nullptr)时,slow节点正好位于倒数第N个节点的前一个节点的位置。

代码

#include <iostream>
#include <memory> //std::shared_ptr

struct Node {
	int value;
	Node* next;
	Node(int value) {
		this->value = value;
		next = nullptr;
	}
};

Node* remove_kth_node(Node * head, int n) {
	if (head == nullptr) {
		return head;
	}
	std::shared_ptr<Node> dummy_node(new Node(-1));
	dummy_node->next = head;
	Node* fast = head;
	Node* slow = dummy_node.get();//注意slow指针在fast前面那个节点
	// fast先走n步
	for (int i = 0; i < n; i++) {
		if (fast == nullptr) {
			return head;
		}
		fast = fast->next;
	}
	// fast走n步后,slow跟fast的距离是(n+1),因为初始化的时候,slow在fast前面
	// slow和fast同时走
	while (fast) {
		slow = slow->next;
		fast = fast->next;
	}
	slow->next  = slow->next->next;//这里假设节点不在堆上,不单独调用delete函数
	return dummy_node->next;
};

void print_result(Node* head, int n, Node* result) {
	// input
	std::cout << "input:" << std::endl;
	Node* p = head;
	while(p) {
		std::cout << p->value << "->";
		p = p->next;
	}
	std::cout << "nullptr" << std::endl;
	std::cout << "n=" << n << std::endl;
	// output
	std::cout << "output:" << std::endl;
	p = result;
	while (p) {
		std::cout << p->value << "->";
		p = p->next;
	}
	std::cout << "nullptr" << std::endl;
}

int main()
{
	// case1: 1->2->3->4->5->nullptr, n=2 ==> 1->2->3->5->nullptr
    Node n1(1), n2(2), n3(3), n4(4), n5(5);
	n1.next = &n2;
	n2.next = &n3;
	n3.next = &n4;
	n4.next = &n5;
	Node *head = &n1;
	Node* result =  remove_kth_node(head, 2);
	print_result(head, 2, result);
	// case2: 1->nullptr, n=1 ==> nullptr
	Node n21(1);
	head = &n21;
	result = remove_kth_node(head, 1);
	print_result(head, 1, result);
	// case3: 1->2->nullptr, n=1 ==> 1->nullptr
	Node n31(1), n32(2);
	n31.next = &n32;
	head = &n31;
	result = remove_kth_node(head, 1);
	print_result(head, 1, result);
	return 0;
}

代码运行结果如下:

input:
1->2->3->5->nullptr
n=2
output:
1->2->3->5->nullptr
input:
1->nullptr
n=1
output:
nullptr
input:
1->nullptr
n=1
output:
1->nullptr

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值