西南科技大学OJ题 单链表上查找算法的实现0955

单链表上查找算法的实现

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

输入

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

输出

找到就输出ok,没找到就输出error。

样例输入

10
1 2 3 4 5 6 7 8 9 10
5

样例输出

ok

#include<stdio.h>
#include<malloc.h>
struct LinkNode
{
    int data;
    struct LinkNode *next;
};

struct LinkNode *Create(int n)
{
    struct LinkNode *head,*p1,*p2;
    head=p1=p2=(struct LinkNode*)malloc(sizeof(struct LinkNode));
    scanf("%d",&p1->data);
    for(int i=1;i<n;i++)
    {
        p2=(struct LinkNode*)malloc(sizeof(struct LinkNode));
        p1->next=p2;
        p1=p2;
        scanf("%d",&p1->data);
    }
    p1->next=NULL;
    return head;
}
int main()
{
    int n,i;
    struct LinkNode *head,*p;
    scanf("%d",&n);
    head=Create(n);
    scanf("%d",&i);
    if(i<=0||i>n)
    printf("error");
    else
    printf("ok");
 } 

/* 
#include<stdio.h>
int main()
{
    int n,a[100],t;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    scanf("%d",&t);
    if(t<=0||t>n)
    printf("error");
    else
    printf("ok");
}
*/ 

猜你喜欢

转载自blog.csdn.net/qq_40593308/article/details/82559751
今日推荐