#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;
}
我无法确定此错误的原因。 Plz帮我guyz。我是C和C ++编程的新手。
答案 0 :(得分:6)
请注意slow->data
为int
,但thirdLastElement
的返回值必须为node*
。您可能想在那里返回slow
,并在程序的主要功能中返回:
cout << " the third last element is : " << thirdLastElement(head)->data << endl;
作为提示:在解释编译器错误消息时,查看消息中的行号,它会告诉您错误的位置。
注意:如果所有指针都无效,请避免使用fast = fast->next->next->next
之类的内容。您正在检查fast
和fast->next
,但忘了查看fast->next->next
。