完整程序,6项基本操作(增删改查、排序加求元素个数)VC++直接运行,这也是我们的基本课程,分享一下
#include
#include
#define OK 1
#define OVERFLOW -2
#define ERROR 0
typedef int ElemType;
typedef int Status;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
void CreateList_L(LinkList &L,int n){
int i;
LinkList p,rear;
L=rear=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
for(i=1;i<=n;i++){
printf("请输入第%d个元素:",i);
p=(LinkList)malloc(sizeof(LNode));
scanf("%d",&p->data);
p->next=NULL;
rear->next=p;
rear=p;
}
}
Status ListInsert_L(LinkList &L,int i,ElemType e){
LinkList p,s;
int j;
p=L;j=0;
while(p&&j
if(!p||j>i-1)return ERROR;
s=(LinkList)malloc(sizeof(LNode));
s->data=e;s->next=p->next;
p->next=s;
return OK;
}
Status ListDelete_L(LinkList &L,int i,ElemType &e){
LinkList p,q;
int j;
p=L;j=0;
while(p->next&&j
}
if(!(p->next)||j>i-1)return ERROR;
q=p->next;p->next=q->next;
e=q->data;free(q);
return OK;
}
Status ChangElem_L(LinkList &L,int i,ElemType e){
LinkList p;
int j;
p=L->next;j=1;
while(p&&jp=p->next;++j;
}
if(!p||j>i)return ERROR;
p->data=e;
return OK;
}
Status GetElem_L(LinkList L,int i,ElemType &e){
LinkList p;
int j;
p=L->next;j=1;
while(p&&jp=p->next;++j;
}
if(!p||j>i)return ERROR;
e=p->data;
return OK;
}
void SortList(LinkList head)
{LinkList p,q,large;int temp;
for(p=head->next;p->next!=NULL;p=p->next)
{large=p;
for(q=p->next;q;q=q->next)
if(q->data>large->data)
large=q;
if(large!=p)
{temp=p->data;
p->data=large->data;
large->data=temp;}
}
}
int CountList(LinkList L){
LinkList p=L;
int c=0;
while(p->next!=NULL)
{c++;
p=p->next;}
return c;
}
void PrintList(LinkList L){
LinkList p;
p=L->next;
do{
printf("%d,",p->data);
p=p->next;
}while(p);
printf("\n");
}
void main()
{int n,e,i,flag;
LinkList L;
printf("请输入元素个数:");
scanf("%d",&n);
CreateList_L(L,n);
printf("原始单链表:");
PrintList(L);
printf("\n请选择要进行的操作:\n1 增,2 删,3 改,4 查,5 排序,6 求元素个数\n输入选择序号:");
scanf("%d",&flag);
switch(flag)
{
case 1:
printf("请输入要插入的元素:");
scanf("%d",&e);
printf("请输入要插入的位置:");
scanf("%d",&i);
ListInsert_L(L,i,e);
printf("改变后的单链表:");
PrintList(L);
break;
case 2:
printf("请输入要删除元素的位置:");
scanf("%d",&i);
ListDelete_L(L,i,e);
printf("改变后的单链表:");
PrintList(L);
break;
case 3:
printf("请输入新的值:");
scanf("%d",&e);
printf("请输入要修改元素的位置:");
scanf("%d",&i);
ChangElem_L(L,i,e);
printf("改变后的单链表:");
PrintList(L);
break;
case 4:
printf("请输入要查找元素的位置:");
scanf("%d",&i);
GetElem_L(L,i,e);
printf("第%d个元素的值是:%d\n",i,e);
break;
case 5:
SortList(L);
printf("从大到小排序后的链表:");
PrintList(L);
break;
case 6:
printf("线性表元素个数:%d\n",CountList(L));
break;
default:
printf("你输入的选择不存在!\n");
break;
}
}