データ構造問題006:秩序テーブルにおける冗長要素の削除(ANSI C)

811 ワード

1、要素が昇順で並べ替えられていると仮定する順序表
/*
 * remove redundant elements from ordered sequence
 */
int remove_redundant_elem( int c[], int n )
{
	int i = 0, j = 1;
	while( j < n )
	{
		if( c[i] != c[j] )
			c[++i] = c[j];
		++j;
	}
	return i + 1;
}

2、要素が昇順で並べ替えられたと仮定する単鎖表
void remove_redundant_elem_llist( link_list * lst )
{
	node_ptr h = *lst, r = NULL, p = NULL;
	assert( h != NULL );
	r = h->next;
	if( r != NULL )
		p = r->next;

	while( p != NULL )
	{
		if( p->data != r->data )
			r = p;
		else
		{
			r->next = p->next;
			free( p );
		}
		p = r->next;
	}
}