#include<stdio.h>
#include<stdlib.h>
typedef struct LNode//构造结点类型
{ int data;
struct LNode *next;
}*LinkList;
void InitList(LinkList &L,int len);//创建链表
void InsertList(LinkList &L,int i,int e);//插入元素
void DeleteList(LinkList &L,int j);//删除元素
void PrintfList(LinkList &L);//输出链表
void DestroyList(LinkList &L);//销毁链表
void main()
{ //在每次链表变换前后都将它输出显示
LinkList La;
int e,k,m,len;
printf("Please input the length of list:");
scanf("%d",&len);
InitList(La,len);
PrintfList(La);
printf("Please input the position to insert and the value of number to insert:\n");
scanf("%d,%d",&k,&e);
InsertList(La,k,e);
PrintfList(La);
printf("Please input the position to delete:");
scanf("%d",&m);
DeleteList(La,m);
PrintfList(La);
DestroyList(La);
}
void InitList(LinkList &L,int len)
{ LinkList p,q;
int i;
if(!(L=(LinkList)malloc(sizeof(LNode))))
{ printf("Fail to create list!\n");
return;
}
L->next=NULL;
L->data=len;
q=L;
for(i=1;i<=len;i++)
{ p=(LinkList)malloc(sizeof(LNode));
printf("Please input a number:");
scanf("%d",&p->data);
p->next=q->next;
q->next=p;
q=p;
}
printf("Success to create list!\n");
}
void InsertList(LinkList &L,int i,int e)
{ LinkList p,q,r;
if(!(p=(LinkList)malloc(sizeof(LNode))))
{ printf("Fail to insert element!\n");
return;
}
p->data=e;
for(q=L->next;i>1;i--)
{ r=q;
q=q->next;
}
if(!r)
printf("Fail to insert element!\n");;
p->next=q;
r->next=p;
printf("Success to insert element!\n");
}
void DeleteList(LinkList &L,int j)
{ LinkList p,q;
int y,z=j;
for(p=L->next;z>1;z--)
{ q=p;
p=p->next;
}
if(!p)
{ printf("Fail to delete!\n");
return;
}
y=p->data;
q->next=p->next;
free(p);
printf("Success to delete number %d!\n",y);
}
void PrintfList(LinkList &L)
{ LinkList p;
printf("The list is:");
for(p=L->next;p;p=p->next)
printf("%d",p->data);
printf("\n");
}
void DestroyList(LinkList &L)
{ LinkList p,q;
for(p=L;p;)
{ q=p;
p=p->next;
free(q);
}
L=NULL;
printf("Success to destroy list,end the operation!\n");
}
单链表的插入与删除
最新推荐文章于 2024-09-10 00:04:27 发布