我试图通过递归实现链表,因为我对此很弱。
问题在于递归本身。 假设我有
*temp
(比如 0x1)= rec_function();
--- 拨打 1
在下一次调用中,如果temp
中的地址从0x1
更改为0x2
(比如说),调用1的输出将存储在0x1
还是0x2
中?
temp
是一个全局变量。
代码(如果有人想看一下)
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
char* data ;
struct node* ptr ;
}node;
node* list = NULL ;
node* temp = NULL ;
node* create_stacked_list(int argc ,char* argv[]){
int i = 0 ;
if(argc == 2 ){
temp = malloc(sizeof(node)) ;
list = temp ;
(*list).ptr = NULL ;
(*list).data = argv[1] ;
return list ;
}
else{
temp = malloc(sizeof(node)) ;
(*temp).data = argv[argc -1 ] ;
argv[argc - 1 ] = NULL ;
argc-- ;
if(i==0) {list = temp ;}
temp -> ptr = create_stacked_list(argc ,argv);
printf("line28");
//list = temp ;
return list ;
}
i++;
} ;
int main(int argc , char * argv[]){
//format :elements in list as a stack ;
//create the list ;
list = create_stacked_list(argc,argv) ;
node* ptr = (*list).ptr ;
while ( ptr != NULL ) {
printf("%s\n" , (*(ptr)).data);
printf("%p \n " , ptr );
ptr = (*ptr).ptr;
}
}
你必须首先学会编写可读的代码,为了别人,也为了你自己。正确的缩进是发现代码中问题的关键。