从有序表中删除所有其重复的元素,是表中所有元素的值均不同
#include<iostream>
#include<stdlib.h>
#define Size 12
using namespace std;
typedef struct Table {
int* head;
int length;
int size;
}table;
table InitTable()
{
table t;
t.head = (int*)malloc(Size * sizeof(int));
if (!t.head)
{
printf("创建空间失败");
return t;
}
t.length = 0;
t.size = Size;
return t;
}
void displayTable(table t)
{
for (int i = 0; i < t.length; i++)
{
printf("%d ", t.head[i]);
}
printf("\n");
}
bool delTable(table& t)
{
if (t.length <= 0)
return false;
int i, j;
for (i = 0, j = 1; j < t.length; j++)
{
if (t.head[i] != t.head[j]) //比较前后两个元素的值
t.head[++i] = t.head[j];
//1、i的值代表不重复元素的下标,用来记录不同元素的值,j来循环判断。
//2、这里因为是++i,所以在赋值语句t.head[++i]= t.head[j],i的值是从1开始。
//3、前后两个值不相同就记录。i的值就+1,否则i不变。
//4、循环结束后顺序表的长度要更新i+1为顺序表的长度。
//5、本道题运用了++i和j++的区别,如果j=1,i=0那么循环结果会一直相同。除非条件判断不成立。
}
t.length = i + 1;
return true;
}
int main()
{
table t;
t = InitTable();
for (int i = 0; i < t.size; i++)
{
cin >> t.head[i];
t.length++;
}
delTable(t);
displayTable(t);
return 0;
}