Reputation: 2459
I am met a segfault during implementing my own linked_list in C++. I spent hours on it but still cannot figure out the bug. Any help will be appreciated. Thank you in advance.
I think the error is in find_kth1() function, but I don't know what i do wrong. I can print the linked list just as expected.
/*
*
* find kth to last element in a singly linked list
*/
#include <iostream>
// #include "../linked_list.h"
using namespace std;
struct Node {
int data ;
struct Node *next;
};
Node* push(Node *head, int d){
// push to top
Node *n = new Node;
n->data = d;
n->next = head;
return n;
}
void print_LL( Node* head){
Node* p = head;
while(p) {
cout << p->data << ' ';
p = p->next;
}
}
int find_length( Node* head) {
int len = 0;
Node* p = head;
while(p){
len ++;
p = p->next;
}
return len;
}
Node* find_kth1( Node* head, int k){
// find length, scan twice
int len = find_length(head);
Node *p = head;
int i = 0;
while( i < len-k){
i ++ ;
p = p->next;
}
return p;
}
int main( void){
Node *head;
head = push( head, 2) ;
head = push( head, 3) ;
head = push( head, 4) ;
head = push( head, 5) ;
head = push( head, 2) ;
print_LL( head);
int k = 3;
Node *p = find_kth1( head, k);
// cout<<p->data<<endl;
}
Upvotes: 0
Views: 101
Reputation: 13425
The head pointer need to be initialized
It is used with out initialization
Normally compiler gives warning , so always heed to the warnings
Node *head=NULL;
Upvotes: 4