线性表的交换
/*目的:将线性表(a1,a2,…,am,b1,b2,…,bn)改变成(b1,b2,…,bn,a1,a2,…,am)。
*/
# include <stdio.h>
# include <stdlib.h>
#define LIST_INIT_SIZE 80 // 线性表存储空间的初始分配量
#define LISTINCREMENT 10 // 线性表存储空间的分配增量
typedef char ElemType;
typedef struct
{
ElemType *elem; // 存储空间基址
int length; // 当前长度
int listsize; // 当前分配的存储容量
int incrementsize; // 约定的增补空间量
}SqList;
// 构造一个空的线性表
void InitList_Sq(SqList &L)
{
L.elem= (ElemType *) malloc (LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)
printf("分配失败\n");
L.length=0;
L.listsize=LIST_INIT_SIZE; //已修改
L.incrementsize = LISTINCREMENT;
}
//初始化线性表
void InputElem_Sq(SqList &L)
{
int i;
char ch;
printf("input a string:\n");
for(i=0;(i<100)&&((ch=getchar())!=EOF)&&(ch!='\n');i++)
{
L.elem[i]=(char)ch;
}
L.elem[i]='\0';
L.length=i;
printf("input was :%s, L.length=%d\n",L.elem, L.length);
}
//改变线性表
SqList exchange_1(SqList &La, int m, int n)
{
SqList Lb;
int i, j;
Lb.length = 0;
for (i=0; i<La.length; i++)
printf("after exchage : %c\n", La.elem[i]);
printf("%d, %d\n", m ,n);
i=0;j=n;
while (j<m+n)
{
Lb.elem[i] = La.elem[j]; //每次运行到这里程序就终止了,这里有啥问题呀
++Lb.length;
i++; j++;
}
i=m;j=0;
while (j<n)
{
Lb.elem[i] = La.elem[j];
++Lb.length;
i++; j++;
}
return Lb;
}
int main()
{
SqList La, Lb;
int m, n;
int i;
InitList_Sq(La);
InputElem_Sq(La);
printf("input m n : ");
scanf("%d%d", &m, &n);
Lb = exchange_1(La, m, n);
for (i=0; i<m+n; i++)
printf("after exchage : %c", Lb.elem[i]);
return 0;
}
[此贴子已经被作者于2016-3-4 19:26编辑过]