I am writing a program to find the nth
to the last node in a linked list. The program produces the correct output, however, when I run the program I get a segmentation fault at the line while(fast)
. When I debugged the program using print statements, I noticed while(fast)
gets executed even when fast
pointer is NULL
(i.e. fast
goes beyond the end of the list).
Any suggestions on how to fix the segmentation error?
Here's my code:
#include <vector>
#include <iostream>
using namespace std;
struct Node {
public:
int data;
struct Node* next;
};
void insert(Node*& headPtr, int val) {
Node* temp = new Node;
temp->data = val;
temp->next = headPtr;
headPtr = temp;
}
Node* mth_to_last(Node* head, int m) {
Node* fast = head;
Node* slow = head;
for(int i = 0; i < m; i++) {
fast = fast->next;
}
while(fast) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
int main() {
Node* head;
for(int i = 10; i >= 1; i--) {
insert(head, i);
}
Node* res = mth_to_last(head, 4);
cout << res->data << endl;
}