链表:查找链表倒数第k个数
#include<iostream>
using namespace std;
typedef struct stu
{
int num;
stu* next;
}node,*nodelist;
nodelist creat_list(nodelist L)
{
int n;
cout<<"请输入要添加的学生人数"<<endl;
cin>>n;
while(n--)
{
nodelist p=new node;
p->num=n;
p->next=L;
L=p;
}
return L;
}
void display(nodelist L)
{
nodelist p;
for(p=L;p!=NULL;p=p->next)
{
cout<<p->num<<" ";
}
}
void output_result(int k,nodelist L)
{
nodelist p1,p2;
p1=p2=L;
int temp=k;
k--;
while(k--)
{
p2=p2->next;
}
while(p2->next!=NULL)
{
p1=p1->next;
p2=p2->next;
}
cout<<"倒数第"<<temp<<"数为"<<p1->num<<endl;
}
int main()
{
nodelist L=NULL;
L=creat_list(L);
display(L);
cout<<"请输入要查找倒数第几个数"<<endl;
int k;
cin>>k;
output_result(k,L);
while(L)
{
nodelist temp=L;
L=L->next;
delete temp;
}
return 0;
}