我把这三个小题合到一起写了
关于算法看一下每个函数
简单的
第一题我是先把26插到链表最后
再用一个”正序排列”函数,排列一下
数据递减有序用的是”逆序函数”(其实就是正序里面把>号改成<号就好了,
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
typedef int ElemType;
typedef struct LNode {
ElemType date;
struct LNode *next;
}linklist,*link;
////////////////////////////////////////////// /////////
// /*插入结点*/////////////// ///////////////////////
int listinsert(link &L,int i,ElemType e)
{
link p,q;int j;
p=L;j=0;
while(p&&j<i-1)
{p=p->next;++j;
}q= (link)malloc(sizeof(LNode));
q->date=e;
q->next=p->next;
p->next=q;
return 1;
} ///////////////////////////////////
/////////////////////////////////////
void show(link l)
{ link p; int j;
p=l;j=0;
cout<<"链表的值为:\n";
while(p->next)
{cout<<p->next->date<<endl;
p=p->next;
}} ///////////////////////////////////////
////正序排列/////////////////////////////////////////
void putline(link &l)
{if(l==NULL ||l->next==NULL )
cout<<"链表未建立或是空的,请先构造链表\n" ;
else{
link p,q;
p=l->next;
while(p!=NULL)
{ q=p->next;
while(q!=NULL)
{ if(p->date>q->date)
{ ElemType t;
t=p->date;
p->date=q->date;
q->date=t;
} q=q->next;
}
p=p->next;
}}}
///////////////////////////////////////////////
///////////// 逆序排列/ ///////////////
void fputline(link &l)
{
if(l==NULL ||l->next==NULL )
cout<<"链表未建立或是空的,请先构造链表\n" ;
else{
link p,q;
p=l->next;
while(p!=NULL)
{ q=p->next;
while(q!=NULL)
{ if(p->date<q->date)
{ ElemType t;
t=p->date;
p->date=q->date;
q->date=t;
} q=q->next;
} p=p->next;
}}}
//////////////////////////////////////////////////////////////
int listdelete(link &L,int i,ElemType &e)
{
link p,q; int j;
p=L;j=0;
while(p->next&&j<i-1)
{
p=p->next;++j;
} q=p->next;
p->next=q->next;
e=q->date;free(q);
cout<<"结点已经删除\n";
return 1;
}
//////////////////////////////////////////////////////////
main()
{int i=1,j;
link L=NULL;int a[7]={12,13,21,24,28,30,42 };
if(L)delete L;
L= (link)malloc(sizeof(LNode)) ;
if (!L) exit(1);
L->next=NULL;
cout<<"链表已经建立\n";
for(;i<=7;i++)
listinsert(L,i,a[i-1]) ;
show(L);
cout<<"--------------------\n";
while(1)
{ cout<<"输入1插入数据\n"<<"输入2删除最小节点\n"<<"输入3递减排序\n";
int yy;
cin>>yy;
switch(yy)
{
case 1:
cout<<"--------------------\n输入要插入的值\n";
cin>>j;
listinsert(L,i,j) ;
putline(L);
show(L);
cout<<"--------------------\n ";
break;
case 2: int e;
putline(L);
listdelete(L,1,e);
show(L);
cout<<"--------------------\n ";
break;
case 3: fputline(L);
show(L); break;
default: break;
}} }
温馨提示:答案为网友推荐,仅供参考