使用递归实现CS50链表

问题描述 投票:0回答:1

我试图通过递归实现链表,因为我对此很弱。

问题在于递归本身。 假设我有

*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;

}









}
c cs50
1个回答
0
投票

你必须首先学会编写可读的代码,为了别人,也为了你自己。正确的缩进是发现代码中问题的关键。

© www.soinside.com 2019 - 2024. All rights reserved.