急求:用C的堆栈和链表什么的怎么编 整数的拆分??C语言高手进来让我膜拜一下吧~

2024-12-12 16:20:01
推荐回答(2个)
回答1:

#include
#include

#define IN 1
#define OUT 0

typedef struct link
{
int data;
struct link *next;
}stud;

stud *build();
void *print( stud *h );
void *push( stud *h, int n );
int *pop( stud *h );

int main( void )
{
stud *head;
int done;
int select, *num, value;

head = build();

done = IN;
while( done == IN )
{
printf( "\n*---------------------------------------*" );
printf( "\n*--- 1.Input the struck number. ---*\n" );
printf( "*--- 2.Output the struck number. ---*\n" );
printf( "*--- 3.Exit. ---*\n" );
printf( "*---------------------------------------*" );
printf( "\nEnter you choise: " );
scanf( "%d", &select );

if( select == 3 )
{
done = OUT;
}

switch( select )
{
case 1: printf( "\n\tPush the number in struck:" );
scanf( "%d", &value );
push( head ,value );
print( head );
break;

case 2: printf( "\n\tPop the number from struck.\n" );
num = pop( head );
printf( "\n\tOutput number is %d.\n", num );
break;

case 3: break;

default: printf( "\nPlease choise print number.\n" );
}
}

printf( "\n/--------------------/\n" );
printf( "/-- End operation. --/\n" );
printf( "/--------------------/\n" );
system( "pause" );
return 0;
}

void *print( stud *h )
{
stud *top;

top = h -> next;

while( top != NULL )
{
printf( "\nThe number start top - bottom:" );
printf( "[%d] ", top -> data );
top = top -> next;
}
return 0;
}

stud *build() // 创建链表
{
stud *h, *p; // head 链表的头部, *p 当前的指针

if( ( h =(stud *)malloc(sizeof( stud ))) == NULL )
{
printf( "Malloc Error.\n" );
exit(0);
} // 给链表的头部申请空间

h -> data = 0;
h -> next = NULL;
p = h; // 把*p 指向 链表的头部

return h;
}

void *push( stud *h, int n )
{
stud *new_node, *p; // new_node 新的节点

p = h;

if( ( new_node = (stud * )malloc( sizeof( stud ))) == NULL )
{
printf( "Malloc Errror.\n" );
exit(0);
} // 为新的节点分配存储空间

new_node -> next = p -> next; // 让 *p始终在堆栈的最前面,新节点new_node 压入栈中(链表)
p -> next = new_node;
new_node -> data = n; // 给新节点的数据区赋值
p = new_node; // 新节点作为栈顶
return 0;
}

int *pop( stud *h )
{
stud *p; // 当前指针
int *temp;

if( h -> next != NULL )
{

p = h; // 指向首部
h = h -> next; // 首部下移一位
temp = p -> data; //编译工具一直报错,但不清楚为何错了。
free( p );
return temp;
}
print( h );
else
return 0;
}

回答2:

什么链表,堆栈的,不用。直接回溯即可
// Integer partition, didn't remove dup yet, typical case of backtracking

#include
using namespace std ;

int a[100] ;

void Output(int *a, int n)
{
for (int i = 0; i < n; i++)
cout << a[i] << " " ;
cout << endl ;
}

void Partition(int n, int t)
{
if(n < 0)
return ;

if (n == 0)
Output(a, t) ;
else
{
for (int i = 1; i <= n; i++)
{
a[t] = i ;
Partition(n - i, t + 1) ;
}
}
}

int main(void)
{
Partition(5, 0) ;

system("pause") ;
return 0 ;
}