从一个有序顺序表中删除重复的元素

/* 
	从一个有序顺序表中删除重复的元素并返回新的表长,要求空间复杂度为O(1);
*/
# include 

typedef int ElemType;
typedef struct {
	ElemType data[100];
	int length;
}SqList;

	
int removeSame1(SqList &B) {				//解法一
    int index = 1;

    for (int i = 1; i < B.length; i++) {
        if (B.data[i] != B.data[index-1])
            B.data[index++] = B.data[i];
    }
    return index;
}

int removeSame2(SqList &B) {				//解法二								
	ElemType e = B.data[0];
	int index = 1; 

	for (int i = 1; i < B.length; ++i) {
		if(B.data[i] != e) {
			B.data[index++] = B.data[i]; 
			e = B.data[i];
		}
	}
	return index;
}	

int main() {
	SqList R;
//	int A[] = {1, 2, 2, 1, 3, 4, 5, 4, 2, 1};
	int i;
	int A[] = {1, 2, 2, 3, 3, 3, 4, 4, 5, 5};

	for (i = 0; i < sizeof(A)/4; ++i)         //顺序表初始化
		R.data[i] = A[i];
	R.length = i;

//	R.length = removeSame1(R);				  //删除重复元素并返回删除后的表长
	R.length = removeSame2(R);

	printf("删除前:\n");					
	for (i = 0; i < sizeof(A)/4; ++i)
		printf("%2d", A[i]);
	printf("\n");

	printf("删除后:\n");
	for (i = 0; i < R.length; ++i)			  
		printf("%2d", R.data[i]);
	printf("\n");

	return 0;
}
/*
	在Vc++6.0中的输出是:
					删除前:
					 1 2 2 3 3 3 4 4 5 5
					删除后:
					 1 2 3 4 5
*/


你可能感兴趣的:(数据结构与算法)