Question

In: Computer Science

When I run this, gdb gives me a segmentation fault at the for loop. It says...

When I run this, gdb gives me a segmentation fault at the for loop. It says I'm dereferencing curr with curr->data when curr is null. It doesn't even seem to enter the body of the loop sometimes. I am testing it on a linked list that ends with a strange element. Could you help me get this one done? Thanks so much! Here is the instruction and code:

LewList *splitStrange();

This function should split the list in two, adding the elements with "strange" values into a new linked list, and keeping only those elements with "normal" (i.e. not strange) values in the list object on which this function is called. The function should return a pointer to the new (heap allocated) list with the strange elements in it. If the original list is empty, or if there are no strange elements, the function should return a pointer to a new empty LewList (not a pointer to nullptr).

We define "strange" for integers as "odd". (Look it up... odd is a synonym for strange!). See Strange.h for function templates defining a strange() function implementing this. Your implementation of splitStrange() should call strange() to determine whether to keep a particular element.

Sample Behavior

If the original list contains integers 3, 4, 18, 2, 9, 1, 10, 22, and 233, then this function should return a pointer to a new LewList containing integers 3, 9, 1, and 233 (in any order). And the original list should be altered to contain only integers 4, 18, 2, 10, and 22 (in any order).

// splitStrange()
template <typename ElementType>
LewList<ElementType> *LewList<ElementType>::splitStrange()
{
   LewList<ElementType> *rlist = new LewList<ElementType>;
   ElementType strangeval;
   if(num_elements == 0)
   {
       return rlist;
   }
   Node*curr = list_head;
   Node*temp = nullptr;
   Node*prev = list_head;
   while(curr != nullptr)
   {
       if(strange(curr->nullptr))
       {
           strangeval = curr->data;
           for(curr = list_head; curr->data != strangeval; curr = curr->next)
           {
               prev = curr;
               std::cout<<curr->data;
           }
           prev->next = curr->next;
           temp = curr;
           curr = curr->next;
           delete temp;
           num_elements--;
           rlist->insert(strangeval);  
       }
       else
       {
           curr = curr->next;
       }
   }
   return rlist;
}

//Strange.h

template <typename ElementType>
bool strange(const ElementType &element) {
   return true;
}

bool strange(const int &element) {
   return (element % 2);
}

Solutions

Expert Solution

There are some changes you need to make. I am using comment here to mark your mistake and make desired changes in your code.

LewList<ElementType> *LewList<ElementType>::splitStrange()
{
   LewList<ElementType> *rlist = new LewList<ElementType>;
   ElementType strangeval;
   if(num_elements == 0)
   {
       return rlist;
   }
   Node*curr = list_head;
   Node*temp = nullptr;
   Node*prev = list_head;
   while(curr != nullptr)
   {
       if(strange(curr->data))/// Strange check for int value 
       {
           strangeval = curr->data;
           for(curr = list_head; curr->data != strangeval; curr = curr->next)
           {
               prev = curr;
               std::cout<<curr->data;
           }
           prev->next = curr->next;
           temp = curr;
           curr = curr->next;
           delete temp;  ///As asked in question you should not delete this but leave remaining list
           num_elements--;
           rlist->insert(strangeval);  
       }
       else
       {
           curr = curr->next;
       }
   }
   return rlist;
}

I hope now this will work fine. If you could provide structure of list, I could test for output.


Related Solutions

when i run the program on eclipse it gives me this error: Exception in thread "main"...
when i run the program on eclipse it gives me this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0    at SIM.main(SIM.java:12) how do I fix that ? (please fix it ) import java.util.*; import java.util.Scanner; import java.util.ArrayList; import java.io.File; import java.io.FileNotFoundException; import java.lang.Math; public class SIM{    public static void main(String[] args) throws FileNotFoundException {       int cacheSize = Integer.parseInt( args[1] ); int assoc = Integer.parseInt( args[2] ); int replacement = Integer.parseInt(...
I cannot get this code to run on my python compiler. It gives me an expected...
I cannot get this code to run on my python compiler. It gives me an expected an indent block message. I do not know what is going on. #ask why this is now happenning. (Create employee description) class employee: def__init__(self, name, employee_id, department, title): self.name = name self.employee_id = employee_id self.department = department self.title = title def __str__(self): return '{} , id={}, is in {} and is a {}.'.format(self.name, self.employee_id, self.department, self.title)    def main(): # Create employee list emp1...
Please provide assistance to fix the segmentation fault error I am receiving and solve the following...
Please provide assistance to fix the segmentation fault error I am receiving and solve the following problem I am working on: My goal is to build a Trie data structure in C++ that can do the following: - Capable to insert any given dictionary .txt file filled with a single word per line (i.e. file includes ant, bat, car, desk, etc.) into the Trie. A sample dictionary file that I'm working with can be found at http://txt.do/1pht5 - Prompts the...
I get confused when it gives me a list of data instead of numbers to input...lol....
I get confused when it gives me a list of data instead of numbers to input...lol. HELP! You wish to test the following claim ( H a ) at a significance level of α = 0.05 . H o : μ = 65.8 H a : μ < 65.8 You believe the population is normally distributed, but you do not know the standard deviation. Data 77.9 49.7 49.0 64.7 51.9 48.2 51.4 58.6 53.7 63.2 68.0 54.1 70.1 55.9 70.7...
1.My roommate/mom asks me to buy milk when I go to the grocery store. She gives...
1.My roommate/mom asks me to buy milk when I go to the grocery store. She gives me $5. What has formed between us? A. A partnership B.An agent relationship C.An internship D.A contract 2.Chicos Tacos opens a taco truck on Mesa. Lines form at the truck as West Siders finally get convenient access to Chicos. 2 weeks later, Little Diner opens a Gordita stand across the street, and Carlos & Mickey’s opens a margarita cart next door, capitalizing on the...
Hello, I Have create this code and Tried to add do while loop but it gives...
Hello, I Have create this code and Tried to add do while loop but it gives me the error in string answar; and the areas where I blod So cloud you please help me to do ( do while ) in this code. // Program objective: requires user to input the data, program runs through the data,calcualtes the quantity, chacks prices for each iteam intered,calautes the prices seperatly for each item, and calculates the amount due without tax, and then...
what does it mean when it says, " an allele confers with a phenotype" ? I...
what does it mean when it says, " an allele confers with a phenotype" ? I need a synonym or different short simple explanation of this statement.
Python 3 In the field where it says failure day indicate current date if i run...
Python 3 In the field where it says failure day indicate current date if i run the program today it show todays date and if i run the program tomorrow it show me tomorrows date and so on . The program is rewriting the product everytime it gets executed i want to add new products as a list in excel # required library import tkinter as tk from tkcalendar import DateEntry import xlsxwriter # frame window = tk.Tk() window.title("daily logs")...
Python 3 In the field where it says failure day indicate current date if i run...
Python 3 In the field where it says failure day indicate current date if i run the program today it show todays date and if i run the program tomorrow it show me tomorrows date and so on . The program is rewriting the product everytime it gets executed i want to add new products as a list in excel # required library import tkinter as tk from tkcalendar import DateEntry import xlsxwriter # frame window = tk.Tk() window.title("daily logs")...
How would I write a C++ code that gives me the following out put:    Enter...
How would I write a C++ code that gives me the following out put:    Enter count of male students: 14 Enter count of female students: 17 Students registered Total:    31 Male:     14   45.16% Female:   17   54.84%    Enter count of male students: 7 Enter count of female students: 2 Students registered Total:     9 Male:      7   77.78% Female:    2   22.22%            */
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT