#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct Lnode
{
ElemType data;// int型数据域
struct Lnode *next;
}LNode,*LinkLIst;
//Lnode* 是结构体指针,和LinkLIst完全等价的。
void list_head_insert(LNode* &L)
{
L=(LinkLIst)malloc(sizeof(LNode));//申请头节点空间,头指针指向头节点
L->next=NULL;
ElemType x;
scanf("%d",&x);
LNode *s; //用来指向申请的新节点
while(x!=9999)
{
s=(LinkLIst)malloc(sizeof(LNode));//先申请空间避免9999也被输入进来
s->data=x;
s->next=L->next; //s的next指向原本链表的第一个节点
L->next=s;
scanf("%d",&x);
}
}
//-------尾插法----------
void list_tail_insert(LNode* &L)
{
L=(LinkLIst)malloc(sizeof(LNode));//申请头节点空间,头指针指向头节点
L->next=NULL;
ElemType x;
scanf("%d",&x);
LNode *s,*r=L; //s用来指向申请的新节点 r是始终指向链表尾部
while(x!=9999)
{
s=(LinkLIst)malloc(sizeof(LNode));//为新节点申请头节点空间,头指针指向头节点
s->data=x;
r->next=s;
r=s;//r要指向新的尾部
scanf("%d",&x);
}
r->next=NULL;//尾节点的next为NULL
}
//------链表打印-----------
void print_list(LinkLIst L) //只读不改动 不需要C++引用
{
L=L->next;
while(L!=NULL)
{
printf("%3d",L->data);
L = L->next;
}
printf("\n");
}
//-----按位置查找GetElem()函数-------
LinkLIst GetElem(LinkLIst L,int SearchPos)
{
int i=0;
if(SearchPos<0)
{
return NULL;
}
while(L&&i<SearchPos)//L 即为L为 L!=NULL
{
L=L->next;
i++;
}
return L;
}
//-------按值查找---------------
LinkLIst LocateElem(LinkLIst L,ElemType SearchVal)
{
while(L)//L!=NULL
{
if(L->data==SearchVal)
{
return L;
}
L=L->next;
}
return NULL;
}
//------第i个位置插入元素----------
bool ListFrontInsert(LinkLIst L,int i,ElemType InsertVal)
{
LinkLIst p=GetElem(L,i-1);
if(NULL==p)
{
return false;
}
LinkLIst q;
q=(LinkLIst)malloc(sizeof(LNode));//申请头节点空间,头指针指向头节点
q->data=InsertVal;
q->next=p->next;
p->next=q;
return true;
}
int main() {
LinkLIst L,search;//L是链表头指针,是结构体指针类型
// list_head_insert(L);
list_tail_insert(L);
print_list(L);
-------按位置查找-------
// search=GetElem(L,2);
// if(search!=NULL)
// {
// printf("Succsees in searching by serial number\n ");
// printf("%d\n",search->data); //指针指向的数据(访问数据)search返回的是指针
// }
//
-------按值查找---------------
// search=LocateElem(L,6);//按值查询
// if(search!=NULL)
// {
// printf("Search by value succeed\n");
// printf("%d\n",search->data);
// }else{
// printf("Failed\n");
// }
//-----往第i个位置插入元素--------
ListFrontInsert(L,2,99);
print_list(L);
return 0;
}
09-20
1258
05-23
1700
04-20
582
09-04
640
07-29
1510