http://www.hackerschool.org/HS_Boards/view.php?id=books&no=1582 [º¹»ç]
Ã¥¿¡ ³ª¿ÍÀÖ´Â ¼Ò½ºÀä...put_heap() ÇÔ¼ö¿¡¼
temp = (int *)malloc( count * sizeof(int) );
if( temp == NULL )
return 0;
À§ ¼Ò½ººÎºÐ¿¡¼ (int *)malloc()¿¡¼ count = 0À϶§ (int *)malloc(0)ÀÌ µÇ´Âµ¥
Àç »ý°¢¿¡´Â À̶§ temp¿¡ NULL °ªÀÌ µé¾î°¡´Â °Í °°°Åµç¿ä ½ÇÁ¦·Î ÄÄÆÄÀÏÇؼ
½ÇÇàÇغ¸¸é Ã¥¿¡ ÀÖ´Â ¼Ò½º ´ë·Î¶ó¸é °è¼Ó À§ºÎºÐ¿¡¼ 0°ªÀÌ °è¼Ó ¸®ÅÏ µÇ¼
½ÇÇàÀÌ µÇÁö ¾Ê½À´Ï´Ù..¸Û¸Û´Ô ÀÌ°Å ÇØ°áÁ» ÇØÁÖ¼¼¿ä ¾Æ·¡´Â Àüü ¼Ò½º±¸¿ä..
/* pre_processing command */
#include <stdio.h>
#include <stdlib.h>
/* variables announce */
int *heap, count;
/* function prototypes announce */
int create_heap( void );
int put_heap( int data );
int get_heap( void );
void clean_heap( void );
/* structure define */
/* main() function define */
int main( void )
{
int n,d;
create_heap();
while( 1 ){
printf( "\n--------------------\n" );
printf( "1. Put a data\n" );
printf( "2. Get a data\n" );
printf( "3. Exit\n" );
printf( ">" );
scanf( "%d", &n );
if( n == 3 )
break;
if( n == 1 ){
printf( "Enter a number\n" );
printf( ">" );
scanf( "%d", &d );
put_heap( d );
continue;
}
if( n == 2 ){
d = get_heap();
if( d != -1 )
printf( "Number is %d.\n", d );
else
printf( "No data.\n" );
continue;
}
}
clean_heap();
return 1;
}
/* function define */
/* create_heap() define */
int create_heap( void )
{
count = 0;
heap = (int *)malloc( 1 );
if( heap == NULL ){
return 0;
}
return 1;
}
/* put_heap() define */
int put_heap( int data )
{
int *temp;
temp = (int *)malloc( count * sizeof(int) );
if( temp == NULL )
return 0;
memcpy( temp, heap, count * sizeof(int) );
free( heap );
count += 1;
heap = (int *)malloc( count * sizeof(int) );
if( heap == NULL )
return 0;
heap[0] = data;
memcpy( heap+1, temp, (count-1) * sizeof(int) );
free( temp );
return 1;
}
/* get_heap() define */
int get_heap( void )
{
int *temp,value;
if( count == 0 ){
return -1;
}
temp = (int *)malloc( count * sizeof(int) );
if( temp == NULL ){
return -1;
}
memcpy( temp, heap, count * sizeof(int) );
free( heap );
count -= 1;
heap = (int *)malloc( count * sizeof(int) );
if( heap == NULL )
return -1;
memcpy( heap, temp, count * sizeof(int) );
value = temp[count];
free( temp );
return value;
}
/* clean_heap() define */
void clean_heap( void )
{
free( heap );
}
|
Hit : 939 Date : 2003/05/18 06:07
|