Insert into linked list

This is my first c++ class, and have been through java and vb classes.

I have an assignment to insert items into a linked list based on dates descending. Through the last few days I've attempted to figure out why I continue to receive a segmentation fault (core dumped) error.

I've ensured the item.isLessThan() method is working correct it tests out to identify true or false based on dates.

I had the list working and printing unsorted a day ago. Adding in the sort has proved a headache...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using namespace std;
#include <iostream>
#include <cstring>
#include "List.h"

void List::insertItem(Item & item){
	Item *temp = head;
	
	if ( temp == NULL ){
		head = &item;
	}else {	
		if( !item.isLessThan(temp) ){
			item.setNextPtr(temp);
			head = &item;
			return;
		}
		
		Item *previous;
		temp = temp->getNextPtr();
		
		while (temp->getNextPtr() != NULL){
			previous = temp;
		
			if ( !item.isLessThan(temp) ){
				previous->setNextPtr(&item);
				item.setNextPtr(temp);
				return;
			}
			
			temp = temp->getNextPtr();
		}

		if(previous != NULL){
			previous->setNextPtr(&item);
			item.setNextPtr(temp);
		}else{
			temp->setNextPtr(&item);
		}
	}
}
Last edited on
Topic archived. No new replies allowed.