单链表上查找算法的实现(0955) swust-oj

Description

建立一个长度为n的带头结点的单链表,在该表中寻找第i个结点,若找到,则输出“OK!”,否则输出“error!”。处理数据类型为整型。

input

第一行为链表的长度n; 第二行为链表中的数据元素; 第三行为要找的结点i。

Output

找到就输出“OK!”,没找到就输出“error!”。

Sample Input
10
1 2 3 4 5 6 7 8 9 10
5
Sample Input
OK!

代码:
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
node * next;
}Node;
int total;
void Create(Node*&L,int a[],int n)
{
Node*r,*s;
L=(Node*)malloc(sizeof(struct node));
s=L;
int i;
for(i=0;i<n;i++)
{
s=(Node*)malloc(sizeof(struct node));
s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
void input(Node*&L)
{
int i,a[100];
scanf("%d",&total);
for(i=0;i<total;i++)
{
scanf("%d",&a[i]);
}
Create(L,a,total);
}
bool Insert(Node*L,int i)
{


int j=0;
Node *p;
p=L;
if(i>total||i<=0)
{
return false;
}
while(p!=NULL)
{
j++;
p=p->next;
if(j==i) //找到存在的i
return true;
}
}
int main()
{
Node *L;
input(L);
int i;
scanf("%d",&i);
if(Insert(L,i))
{
printf("OK!");
}
else
printf("error!");
return 0;
}

posted @ 2015-04-07 18:19  殇林  阅读(574)  评论(0编辑  收藏  举报