http://www.hackerschool.org/HS_Boards/zboard.php?id=QNA_programming&no=196 [º¹»ç]
#include <stdio.h>
#include <stdlib.h>
int *heap, count;
int creat_heap( void );
int put_heap( int data );
int get_heap( void );
void clean_heap( void );
int main( void )
{
int c, i;
creat_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", &c );
if( c == 3 )
break;
if( c == 1 )
{
int a = 0;
printf( "Enter a number: " );
scanf( "%d", &i );
put_heap( i );
continue;
}
if( c == 2 )
{
i = get_heap();
if( i != -1 )
printf( "Number is %d.\n", i );
else
printf( "No data.\n" );
continue;
}
}
clean_heap();
return 1;
}
int creat_heap( void )
{
count = 0;
heap = (int *) malloc( 1 );
if( heap == NULL )
return 0;
return 1;
}
int put_heap( int data )
{
int *temp, a;
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 ) );
/* ¿©±â memcpy( heap + 1, temp, (count - 1) * sizeof(int) );
¼³¸íÁ» ÇØÁÖ¼¼¿ä. °è¼ÓºÁµµ À߸ô¸£°Ú³×¿ä */
free( temp );
return 1;
}
int get_heap( void )
{
int *temp, value, a;
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;
}
void clean_heap( void )
{
free( heap );
}
/* Èü¿¡ °üÇؼ º¸´Âµ¥ ±Ã±ÝÇÑ°Å ÀÖ¾î±×·¯´Âµ¥¿ä..int put_heap( int data)
¿©±âÇÔ¼ö¿¡¼ óÀ½¿¡´Â countÃʱⰪÀÌ 0ÀÌÀݽÀ´Ï±î..¼öÇн𣿡 º¸¸é
0 °öÇϱ⠾ ¼ýÀÚÇÏ¸é ´äÀº 0À» °öÇßÀ¸¸é 0À̵Ǵµ¥
(int *) malloc( count * sizeof( int ) ); ¿©±â¼
count * intÇü¸¸Å ¸Þ¸ð¸®ÇÒ´çÇϴµ¥ count°¡ 0ÀÌ¸é ¸Þ¸ð¸®ÇÒ´çÀÌ
¾î¶»°Ô µÇ´Â°Ì´Ï±î?? ±×¸®°í º¸¸é mallocÇÔ¼ö¸¦ ¾µ¶§ (int *)malloc(4)
À̰Ŷû (int *) malloc( sizeof( int ) )À̰Ŷû °°Àº°É·ç ºÁ¾ßÇմϱî?
¸¸ÀÏ °°Àº°Å¶ó¸é ±»ÀÌ sizeof(int)ÀÌ·±°Å ¾È¾²°í ¹Ù·Î malloc( 12 )
ÀÌ·±½ÄÀ¸·Î ½áµÎ µÇ´Â°Å ¾Æ´ÑÁö?±»ÀÌ sizeof( int )ÀÌ·±½Ä¾È½áµÎµÇ´Â°Å
¾Æ´Õ´Ï±î??? */
|
Hit : 3947 Date : 2003/11/12 01:45
|