[英]Unable to compile C++ code: invalid conversion from 'int' to 'node*'
#include<iostream>
using namespace std;
struct node
{
int data;
node* next;
};
void pushList(struct node **head_ref, int element)
{
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->data = element;
temp->next = *head_ref;
*head_ref = temp;
}
void printList(struct node* node)
{
while (node != NULL)
{
cout << node->data << endl;
node = node->next;
}
}
struct node* thirdLastElement(struct node *head)
{
struct node *slow = head;
struct node *fast = head;
if (head == NULL || head->next == NULL)
{
cout << " Required Nodes Are Not Present ";
return 0;
}
fast = fast->next->next->next;
while (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
return(slow->data);
}
int main()
{
struct node* head = NULL;
int n;
cout << " Enter the number of elements " << endl;
cin >> n;
for (int i = 0; i < n; i++)
{
pushList(&head, i);
}
cout << " the list formed is :" << endl;
printList(head);
cout << " the third last element is : " << thirdLastElement(head) << endl;
return 0;
}
I am not able to identify why this error is coming. 我无法确定为什么会出现此错误。 Plz help me guyz . 请帮我盖茨。 I am a newbie to C and c++ programming. 我是C和c ++编程的新手。
Note that slow->data
is an int
, but the return value of thirdLastElement
must be a node*
. 请注意, slow->data
是int
,但是thirdLastElement
的返回值必须是node*
。 You probably wanted to return slow
there, and in the main function of your program: 您可能想在那里slow
返回,并在程序的主要功能中返回:
cout << " the third last element is : " << thirdLastElement(head)->data << endl;
So as a hint: when interpreting compiler error messages, look at the line number in the message, it tells you where the error is. 因此,作为一个提示:在解释编译器错误消息时,请查看消息中的行号 ,它会告诉您错误的位置。
A note: avoid things like fast = fast->next->next->next
without complete checking if all the pointers are valid. 注意:避免使用fast = fast->next->next->next
而无需完全检查所有指针是否有效。 You are checking fast
and fast->next
, but you forgot to check fast->next->next
. 您正在fast
检查fast->next
,但是忘记了检查fast->next->next
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.