作业帮 > 综合 > 作业

有一个长度为n以顺序结构存储的线性表,结点值均为正整数,编写一个算法,把该线性表分解为两个线性表,其

来源:学生作业帮 编辑:百度作业网作业帮 分类:综合作业 时间:2024/05/08 08:07:33
有一个长度为n以顺序结构存储的线性表,结点值均为正整数,编写一个算法,把该线性表分解为两个线性表,其
中一个线性表的结点值均为奇数,另一个线性表的结点值均为偶数.
有一个长度为n以顺序结构存储的线性表,结点值均为正整数,编写一个算法,把该线性表分解为两个线性表,其
//不知道可不可以,你试下
#include
#include
#include
struct node
{
int date;//数据域
struct node *pn;//指针域
};

struct node* init(int x);
void insert(struct node *phead,int pos,int *pval);
bool isempty(struct node *phead);
bool isfull(struct node *phead);
void show(struct node *phead);
int lenth(struct node *phead);

struct node* init(int x)//初始化链表,给链表赋值
{

int val;
struct node *phead=(struct node*)malloc(sizeof(struct node));
if(NULL==phead)
{
printf("内存分配失败!\n");
exit(-1);
}
struct node *ptail;
ptail=phead;
ptail->pn=NULL;
if(x==0)
{
return phead;

}
printf("输入%d个数\n",x);
for(int a=0;adate=val;
ptail->pn=p;
p->pn=NULL;
ptail=p;
}
return phead;
}
void show(struct node *phead)
{
if(phead->pn==NULL)
{
printf("链表为空!\n");
//exit(-1);
}
struct node *p=phead->pn;
while(p!=NULL)
{
printf(" %d ",p->date);
p=p->pn;
}
printf("\n");
}
int lenth(struct node *phead)
{
int len=0;
struct node *p=phead->pn;

while(p!=NULL)
{
len=len+1;
p=p->pn;
}
return len;
}
bool isempty(struct node *phead)
{
if(phead->pn==NULL)
{
return true;
}
else
{
return false;
}
}
bool isfull(struct node *phead)
{
if(phead->pn!=NULL)
{
return true;
}
else
{
return false;
}
}
bool insert(struct node *phead,int pos,int pval)
{
int i=0;
struct node *p=phead;
while(NULL!=p&&ipn;
++i;
}
if(i>pos-1||NULL==p)
{
return false;
}
struct node * pnew=(struct node *)malloc(sizeof(struct node ));
if(NULL==pnew)
{
printf("动态内存分配失败!");
exit(-1);
}
pnew->date=pval;
struct node * q=p->pn;
p->pn=pnew;
pnew->pn=q;
return true;

}
int main()
{
struct node *phead1;//头指针
struct node *phead2;
struct node *phead3;
int pval;
int a=1,b=1;
phead1=init(10);
phead2=init(0);
phead3=init(0);
printf("线性表1中的元素是:\n");
show(phead1);
struct node *p=phead1->pn;
while(p!=NULL)
{
if((p->date)%2==1)
{
insert(phead3,a,p->date);
a++;
}
if((p->date)%2==0)
{
insert(phead2,b,p->date);
b++;
}
p=p->pn;

}
printf("线性表2中的元素(偶数):\n");
show(phead2);
printf("线性表3中的元素(奇数):\n");
show(phead3);
return 0;
}