Don\'t understand why i am getting a seg fault adfter my search function. Header
ID: 3587058 • Letter: D
Question
Don't understand why i am getting a seg fault adfter my search function.
Header:
#ifndef list1_hpp
#define list1_hpp
#include <stdio.h>
#include<iostream>
#include<string>
struct Node{
std::string data;
Node *link;
};
class Lilist{
public:
Lilist(){head = NULL;}
void add(std::string item);
void show();
Node* search(std::string item);
void move_front_to_back();
private:
Node *head;
};
void Lilist::add(std::string item){
Node * tmp;
if(head == NULL){
head = new Node;
head -> data = item;
head -> link = NULL;
}
else{
for(tmp = head; tmp->link != NULL; tmp = tmp -> link)
; // this loop simply advances the pointer to last node in
//the list
tmp ->link = new Node;
tmp = tmp->link;
tmp->data = item;
tmp->link = NULL;
}
}
void Lilist::show(){
for(Node *tmp = head; tmp != NULL; tmp = tmp->link)
std::cout<<tmp->data<<" ";
}
Node* Lilist::search(std::string item){
for(Node* temp = head; temp != NULL; temp = temp->link){
if(temp->data == item)
{
return temp;
}
}
return NULL;
}
void Lilist::move_front_to_back(){
Node *temp;
Node *tail;
temp = head;
for(tail = head; tail -> link != NULL; tail = tail -> link){
head = head -> link;
tail -> link = temp;
temp -> link = NULL;
}
}
#endif /* list1_hpp */
Main:
#include "main.hpp"
#include <iostream>
#include <string>
#include "list1.hpp"
using namespace std;
int main(){
Lilist L1, L2;
string target;
L1.add("Charlie");
L1.add("Lisa");
L1.add("Drew");
L1.add("Derrick");
L1.add("AJ");
L1.add("Bojian");
cout << "Now showing list One: ";
L1.show();
cout<< "Enter a name to search:";
cin>>target;
if(L1.search(target) != NULL)
cout << "That name is stored at address: "<<L1.search(target) <<endl;
else
cout << "That name is not in the list. ";
L1.move_front_to_back();
L1.move_front_to_back();
L1.show();
return 0;
}
Explanation / Answer
void Lilist::move_front_to_back() {
Node *temp;
Node *tail;
temp = head;
for (tail = head; tail->link != NULL; tail = tail->link);
head = head->link;
tail->link = temp;
temp->link = NULL;
}
//Only a simple bracket problem was there.
//It's happen with me and this mistake is really really annoying. Some people called it coder curse.( Solve a extremly //tough problem but run into ample problem due to syntax error).
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.