题目
输入一个长度为 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;
}