请大家看看这个写法那里有问题;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int n=0;
int getDecimalValue(struct ListNode* head){
if(head->next==NULL){
return head->val*num(2,n++);
}else{
return getDecimalValue(head->next)+ head->val*num(2,n++);
}
}
int num(int x,int n){
if(n==0){
return 1;
}else{
return x*num(x,n-1);
}
}
应该不需要递归的计算幂次,只需要把链表从高位到低位遍历一次,然后加上对应位的值就行了
首先要指出上述写法中存在的问题:
函数num
和全局变量n
没有声明。需要先声明函数num
和变量n
,或者将函数num
移到前面以便于调用。
在递归函数getDecimalValue
中,没有对输入的链表指针进行有效性检查,即未考虑到输入链表为空的情况。在递归调用时,应该首先检查head
是否为空指针,如果为空则返回0。
在递归调用时,没有更新全局变量n
的值,导致计算二进制转十进制时的权重出现错误。应该在递归调用前先更新n
的值。
下面是修正后的代码:
int num(int x, int n) {
if(n == 0) {
return 1;
} else {
return x*num(x, n-1);
}
}
int getDecimalValue(struct ListNode* head) {
if(head == NULL) {
return 0;
} else {
n++;
return getDecimalValue(head->next) + head->val*num(2, n-1);
}
}
修正后的代码对输入进行了有效性检查,并在递归调用前更新了全局变量n
的值,保证了二进制转十进制的正确性。同时,修正后的代码也移除了原先未声明的全局变量和函数的问题。
【以下回答由 GPT 生成】
问题所在是在函数getDecimalValue和函数num的调用中存在循环调用的问题。函数getDecimalValue调用了函数num,而函数num又调用了函数getDecimalValue。这导致了递归的无限循环,代码会陷入死循环状态。
为了解决这个问题,我们可以将函数num的实现直接放到函数getDecimalValue中,避免了循环调用的问题。修改后的代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int n = 0;
int getDecimalValue(struct ListNode* head){
int num(int x, int n){
if(n == 0){
return 1;
}else{
return x * num(x, n-1);
}
}
if(head->next == NULL){
return head->val * num(2, n++);
}else{
return getDecimalValue(head->next) + head->val * num(2, n++);
}
}
将函数num的代码移到了getDecimalValue函数内部,解决了循环调用的问题。现在代码可以正确执行。
【相关推荐】