JZ22 链表中倒数最后k个结点

题目

输入一个长度为 n 的链表,设链表中的元素的值为 ai ,输出一个链表,该输出链表包含原链表中从倒数第 k 个结点至尾节点的全部节点。

如果该链表长度小于k,请返回一个长度为 0 的链表。

代码

#include<iostream>
using namespace std;
struct Node
{
	int data;
	Node* next;
};
Node* Create(int n)
{
	Node* p, * h, * s;
	h = new Node;
	h->next = NULL;
	p = h;
	for (int i = 0; i < n; i++)
	{
		s = new Node;
		cin >> s->data;
		p->next = s;
		p = s;
	}
	p->next = NULL;
	return h;
}
void Print(Node* h)
{
	Node* p = h;
	while (p != NULL)
	{
		cout << p->data << "\t";
		p = p->next;
	}
	cout << endl;
}
Node* PrintkList(Node* head1, int k)
{
    if(head1==NULL||k==0)
            return NULL;

	Node* pAhead = head1;
	Node* pBehind = NULL;
	for (int i = 0; i < k - 1; i++)
	{
		pAhead = pAhead->next;
	}

	pBehind = head1;
	while (pAhead->next != NULL)
	{
		pAhead = pAhead->next;
		pBehind = pBehind->next;
	}
	return pBehind;
}
int main()
{
	Node* head1 = new Node;
	head1->next = NULL;
	Node* head2 = new Node;
	head2->next = NULL;
	int i, k;
	cout << "请输入单链表的结点个数:";
	cin >> i;
	cout << "请输入单链表结点的值:";
	head1 = Create(i);
	cout << "请输入从第几位开始从中截取:";
	cin >> k;
	cout << "截取后的链表值是:";
	head2 = PrintkList(head1, k);
	Print(head2);
	return 0;
}

运行结果:

 

知识点

1.用两个指针指向链表,当第一个指针到达k-1的时候,此时再分别继续令两个指针后移,当第一个结点挪到尽头时,此时第二个结点恰好指向要开始打印的结点

(1)Node* pAhead = head1;
         Node* pBehind = NULL;

 (2)for (int i = 0; i < k - 1; i++)
    {
        pAhead = pAhead->next;
    }

 

 (3)pBehind = head1;

 (4)    while (pAhead->next != NULL)
    {
        pAhead = pAhead->next;
        pBehind = pBehind->next;
    }

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值