#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;
}
Run Code Online (Sandbox Code Playgroud)
我无法确定为什么会出现此错误.Plz帮我guyz.我是C和C++编程的新手.
注意slow->data是一个int,但返回值thirdLastElement必须是a node*.你可能想回到slow那里,并在你的程序的主要功能:
cout << " the third last element is : " << thirdLastElement(head)->data << endl;
Run Code Online (Sandbox Code Playgroud)
因此,作为提示:在解释编译器错误消息时,查看消息中的行号,它会告诉您错误的位置.
注意:fast = fast->next->next->next如果所有指针都无效,请避免完全检查.您正在检查fast和fast->next,但你忘了检查fast->next->next.