我创建了一个包含数字的列表。例如:
-3 4 -2 -1 4 5
两个连续节点的产品是-14 -8 2 -4 21
。我想检查两个节点的产品是否总是大于以下节点的乘积。我使用了递归函数,在这个例子中条约不成功,因为2>-4
。
我还想打印一条消息,显示导致问题的第一个节点。在这种情况下,-1是第4个节点。如何返回显示错误节点的指针?请参阅问号:)
struct node* findNode(struct node *junc) {
//Success
if(junc->link->link==NULL){
printf("SUCCESS");
return NULL;
}
//Failure
if (((junc->content)*(junc->link->content))>=((junc->link->content)*(junc->link->link->content))) {
printf("FAIL.");
printf("\nFAIL because of numbers:%d %d.",junc->link->content,junc->link->link->content);
return junc;
}
return(findNode(junc->link));
}
答案 0 :(得分:0)
我想检查两个节点的产品是否总是大于以下节点的乘积。
我认为您的代码方式错误,即您有> =但根据您的说明,它应该是< =
下面的代码将返回指向错误节点的指针(即产品小于或等于接下来两个数字的乘积的两个数字中的第一个)
#include <stdio.h>
struct node {
int content;
struct node* next;
};
struct node* findNode(struct node* node) {
if(node->next->next == 0){
printf("SUCCESS");
return 0;
}
if ((node->content * node->next->content) <= (node->next->content * node->next->next->content)) {
printf("FAIL because of numbers: %d and %d", node->next->content, node->next->next->content);
return node;
}
return(findNode(node->next));
}
int main() {
struct node node1 = {5, 0};
struct node node2 = {4, &node1};
struct node node3 = {-1, &node2};
struct node node4 = {-2, &node3};
struct node node5 = {4, &node4};
struct node node6 = {-3, &node5};
struct node* res = findNode(&node6);
if (res != 0) {
// res is a pointer to the wrong node
}
return 0;
}