7-19 求链式线性表的倒数第K项

#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct note
{
int data;
struct note* next;
}note;
note* CreatList()
{
note *head,*q,*p;
head=(note*)malloc(sizeof(note));
head->next=NULL;
int a;
cin>>a;
p=(note*)malloc(sizeof(note));
p->data=a;
p->next=NULL;
head->next=p;
while(1)
{
cin>>a;
if(a<0)break;
p=(note*)malloc(sizeof(note));
p->data=a;
p->next=head->next;
head->next=p;
}
return head;
}
void Find(note *p,int k)
{
for(int i=1;i<=k;i++)
{
p=p->next;
}
if(p==NULL)
cout<<"NULL"<<endl;
else
cout<<p->data<<endl;
}
int main()
{
int k;
cin>>k;
note *p=CreatList();
Find(p,k);
}

猜你喜欢

转载自www.cnblogs.com/xyfs99/p/10349241.html