void deleterepeat(struct sqlist* L) { if (L->length == 0) printf("表空"); int i = 0; int k = 0; for (i = 1, k = 1; i < L->length; i++) { if (L->a[i] != L->a[i - 1])//遇到后面一个与前一个不相等,就前移 { L->a[k] = L->a[i]; k++; } } L->length = k; }
完整测试代码
#include #define Max 7 struct sqlist { int a[Max]; int length; }; void deleterepeat(struct sqlist* L) { if (L->length == 0) printf("表空"); int i = 0; int k = 0; for (i = 1, k = 1; i < L->length; i++) { if (L->a[i] != L->a[i - 1])//遇到后面一个与前一个不相等,就前移 { L->a[k] = L->a[i]; k++; } } L->length = k; } int main() { struct sqlist L; L.length = 7; int j = 0; for (j = 0; j < L.length; j++) scanf("%d", &L.a[j]); printf("原始顺序表为:"); for (j = 0; j < L.length; j++) printf("%d", L.a[j]); deleterepeat(&L); printf("\n删除重复元素后的顺序表为:"); for (j = 0; j < L.length; j++) printf("%d", L.a[j]); return 0; }