#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;
}
C语言实现头插法、尾插法创建单链表,按值查找、按位查找单链表
最新推荐文章于 2024-07-13 15:11:03 发布