cho một dãy tăng,thêm vào dãy vẫn tăng,chỉ chạy sai trong mỗi trường hợp
cho dãy 1 2 3 4 5 khi thêm vào 3 thì chương trình tự thoát.nhờ anh em sữa giúp
Code:
#include<stdio.h>
#include<conio.h>
#define max 100
typedef struct list
{
int n;
int nodes[max];
};
void nhapds(struct list &ds)
{
printf("nhap vao so phan tu:");
scanf("%d",&ds.n);
printf("nhap danh sach:\n");
for(int i=0;i<ds.n;i++)
{
printf("nhap vao phan tu thu %d:",i+1);
scanf("%d",&ds.nodes[i]);
}
}
void xuatds(struct list &ds)
{
if(ds.n==0)
printf("danh sach rong");
else
{
printf("cac phan tu cua day:");
for(int i=0;i<ds.n;i++)
printf("%d ",ds.nodes[i]);
}
}
void themvaotang(list &ds,int m)
{
if(ds.nodes[0]>=m)
{
for(int i=ds.n-1;i>=0;i--)
ds.nodes[i+1]=ds.nodes[i];
ds.nodes[0]=m;
ds.n++;
xuatds(ds);
}
else if(ds.nodes[ds.n-1]<=m)
{
ds.nodes[ds.n++]=m;
xuatds(ds);
}
else
{
for(int i=0;i<ds.n;i++)
if(ds.nodes[i]<m && m<ds.nodes[i+1])
{
for(int j=ds.n-1;j>i;j--)
ds.nodes[j+1]=ds.nodes[j];
ds.nodes[i+1]=m;
ds.n++;
}
xuatds(ds);
}
}
void main()
{
clrscr();
list ds;
nhapds(ds);
xuatds(ds);
int them;
printf("\nnhap so muon them vao:");
scanf("%d",&them);
themvaotang(ds,them);
getch();
}