#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define NULL 0
#define OK 1
#define ERROR -1
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int Status;
typedef int ElemType;
typedef struct link{
int data;//elemtype类型C本身没有我们通过宏定义创造了它
struct link *next;
}t_link,*pLink;
//定义创建链表的函数
pLink create()
{
int n;
pLink p1,p2,head;
head=p1=(pLink)malloc(sizeof(t_link)); //首先开辟一个内存单元,作为头结点
head->data=0; //头结点数据域为0
if(!head) exit(ERROR); //如果开辟空间失败,退出程序
else{
printf("请输入数据的个数:\n");
scanf("%d",&n);
printf("输入的数据为:\n");
for(int i=1;i<=n;i++)
{
p2=(pLink)malloc(sizeof(t_link)); //开辟新结点
scanf("%d",&p2->data);
p1->next=p2; //连上新结点
p1=p1->next; //指针前移,为下一个结点做准备
}
p1->next=NULL;
} //尾结点指向空,防止出错
return head;
}
//定义遍历函数,让它输出链表的每一个结点的data域值
Status traveser(pLink p)
{
printf("头指针的Data域是%d\n",p->data);
p=p->next; //跳过头指针
printf("链表各个数据为\n");
while(p)
{ //当P不为空值时,循环输出data域
printf("%d ",p->data);
p=p->next;
}
printf("\n");
return true;
}
//在第i个插入e
Status Insert(pLink &L,int i,ElemType e)
{ pLink p,s;
p=(pLink)malloc(sizeof(t_link));
p=L;
int j=0;
while (p&&(j<i-1))
{
p=p->next;
++j;
}
if(!p||j>(i-1))
return ERROR;
s=(pLink)malloc(sizeof(t_link));
s->data=e;
s->next=NULL;
s->next=p->next;
p->next=s;
return OK;
}
//删除第i个
Status Delete(pLink &L,int i)
{ pLink p,q;
p=(pLink)malloc(sizeof(t_link));
p=L;
int j=0;
while((p->next)&&(j<i-1))
{
p=p->next;
++j;
}
if((!p->next)||(j<i-1))
return ERROR;
q=(pLink)malloc(sizeof(t_link));
q=p->next;
p->next=q->next;
free(q);
return OK;
}
//查找
Status GetElem(pLink L,int i)
{
int e;
pLink p;
p=(pLink)malloc(sizeof(t_link));
p=L->next;
int j=1;
while (p&&j<i)
{
p=p->next;
++j;
}
if(!p||j>i)
return ERROR;
e=p->data;
printf("查找的数是%d\n",e);
return OK;
}
void main()
{ pLink h=NULL; //定义h作为链表头,使其指向空,防止错误出现
h=create(); //创建链表,h指向其头结点的内存域
traveser(h); //遍历链表
//插入
int m,x,n,i;
printf("在第m个前面插入元素:\n");
scanf("%d",&m);
printf("插入的元素x为:\n");
scanf("%d",&x);
Insert(h,m,x);
printf("插入后的元素为:\n");
traveser(h); //遍历链表
//删除
printf("删除的元素是第n个:\n");
scanf("%d",&n);
Delete(h,n);
printf("删除后的元素是:\n");
traveser(h); //遍历链表
//查找
printf("查找的数是第i个数\n");
scanf("%d",&i);
GetElem(h,i);
}
实验2 单链表的创建和操作
最新推荐文章于 2023-09-27 21:29:10 发布