C语言实现头插法、尾插法创建单链表,按值查找、按位查找单链表

#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct LNode
{
    ElemType data;
    struct LNode *next;
}LNode,*LinkList;




//头插法创建单链表
void list_head_insert(LinkList &L)
{
    L=(LinkList)malloc(sizeof(LNode));
    ElemType x;
    L->next=NULL;
    scanf("%d",&x);
    LNode *s;
    while(x!=9999)
    {
        s=(LinkList)malloc(sizeof(LNode));
        s->data=x;
        s->next=L->next;
        L->next=s;
        scanf("%d",&x);
    }

}




//尾插法创建单链表
//void list_tail_insert(LinkList &L)
//{
//    L=(LinkList)malloc(sizeof(LNode));
//    ElemType x;
//    L->next=NULL;
//    scanf("%d",&x);
//    LNode *s,*r;
//    r=L;
//    while (x!=9999)
//    {
//        s=(LinkList)malloc(sizeof(LNode));
//        s->data=x;
//        r->next=s;
//        r=s;
//        scanf("%d",&x);
//    }
//    r->next=NULL;
//}



//按位查询
LinkList GetElem(LinkList L,int SearchPos)
{
    int i=0;
    if(SearchPos<0)
    {
        return NULL;
    }
    while(L&&i<SearchPos)
    {
        L=L->next;
        i++;
    }
    return L;
}


//按值查询,可以打印输出所查找的值在链表中的位置
int LocateElem(LinkList L,ElemType SearchVal)
{
    int j=0;
    while(L&&L->data !=SearchVal)
    {
        L = L->next;
        j++;
    }
    if(L)
    {
        printf("%d\n",j);
        return j;

    }else
    {
        printf("false");
        return -1;
    }

}





//打印单链表
void print_list(LinkList L)
{
    L=L->next;
    while(L!=NULL)
    {
        printf("%3d",L->data);
        L=L->next;
    }
    printf("\n");
}
int main()
{
    LinkList L;
    int search;
    list_head_insert(L);
//    list_tail_insert(L);
    print_list(L);
//    search=GetElem(L,6);
//
//    if(search!=NULL)
//    {
//        printf("Succeded in searching by serial number\n");
//        printf("%d\n",search->data);
//    }else{
//        printf("GetElem number=NULL\n");
//    }

    search=LocateElem(L,6);
//    if(search!=NULL)
//    {
//        printf("Search by value succeeded\n");
//        printf("%d\n",search->data);
//    }else{
//        printf("LocateElem number=NULL");
//    }
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值