查找倒数第k个结点
1.题目:
Problem Description
有一单链L,请输出该单链表中倒数第k个结点的值。若该结点不存在,则输出“not find”。
Input
有多组数据,每组第一行为单链表元素个数n和k值(00);第二行为单链表的各元素。
Output
输出该单链表中倒数第k个结点的值。若该结点不存在,则输出“not find”。
Sample Input
5 1
1 2 3 4 5
5 5
1 2 3 4 5
Sample Output
5
1
2.参考代码:
代码一:
#include
using namespace std;
struct Node{
int data;
Node *next;
};
void del(Node *p){
if(p)
del(p->next);
delete p;
}
int main()
{
int n,k,j;
while(cin>>n>>k)
{
Node *root=new Node;
int i,a;
Node *p;
p=root;
for(i=0;i
{
p->next=new Node;
p=p->next;
cin>>a;
p->data=a;
}
p->next=NULL;
if(n
cout<<"not find\n";
else
{
j=n;
p=root->next;
while(p && j>k)
{
p=p->next;
j--;
}
cout<<p->data<<endl;
}
del(root);
}
return 0;
}
代码二:
#include <stdio.h>
#include <malloc.h>
struct node{
int data;
struct node* next;
};
int main()
{
node* root;
root=(node*)malloc(sizeof(node));
root->next=NULL;
int n,k;
while(scanf("%d %d",&n,&k)!=EOF)
{
node* q=root;
for(int i=0;i<n;i++)
{
int a;
scanf("%d",&a);
node* p;
p=(node*)malloc(sizeof(node));
p->data=a;
p->next=q->next;
q->next=p;
q=q->next;
}
if(k>n)
{
puts("not find");
continue;
}
node* p=root;
int c=0;
while(1)
{
p=p->next;
c++;
if(c>=n-k+1)
break;
}
printf("%d\n",p->data);
root->next=NULL;
}
return 0;
}

浙公网安备 33010602011771号