Problem with Insertion and Deletion in custom Linked List Class

I am defining a linked list that has nodes that contain text strings. My problem is twofold. In Part 1, I am trying to insert a node past the farthest node I already have. To reach the new node, I am inserting nodes with blank lines until i get there, then adding my new line. However when i try to do so, my program inserts the new line into the node at the end of the list the returns a segmentation fault and crashes.

This is the code that defines the Node
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

using namespace std;

class NewLine
{
	private:
		string value;
		NewLine* next;

	public:
		NewLine(string stuff);

	friend class LineList;
};

NewLine::NewLine(string stuff)
{
	value = stuff;
}


This is the code for Inserting past the Linked List
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
void LineList::Insert(string text, int linenumber)
{
        ...
	else //Cases for inserting in front of and inside list are handled and work fine
	{
		NewLine* newline = new NewLine(text); //create new node
		newline->next = NULL;

		NewLine* cur;
		cur = head;
		while (cur->next != NULL) //get to end of list
		{
			cur = cur->next;
		}
		while (listsize < linenumber)
		{
			NewLine* blankline = new NewLine(""); //create blank lines until desired line is reached
			blankline->next = NULL;

			cur->next = blankline; //insert blank line at end of list
			listsize++; //update list size
		}
		cur->next = newline; //insert new line at end of list
	}
	listsize++; //Increase list size
}


In Part 2 of my problem, I am trying to delete a Node based on the number it is in my List. So if a user inputs a 3, I would delete the fourth node (i am going on a number system of 0, 1, 2 , etc.). This one also just seg faults and crashes.

Code for Delete function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void LineList::Delete(int linenumber)
{
	NewLine *pre, *ptr;
	pre = NULL;
	ptr = NULL;
	int i = 0;
	while (ptr != NULL) //Go while list is not at end 
	{
		i++;
		if (i == linenumber) break; //Exit if line number is reached
		pre = ptr; ptr = ptr->next;
	}
	if (pre != NULL)
	{
		pre->next = ptr->next; //point to nodes around line to be deleted
	}
	else // the first node is to be deleted 
	{
		head = ptr->next;
	}
	delete ptr; //remove line from existence, deallocate memory
	listsize--;
}


I've already used debugger to try and find problem but I still cannot find out what is causing it.
Thank you all in advance for any help you can provide
snippet 1
---------
line 11: What if cur is NULL?

Line 20: You never advance cur after inserting the blank line.
 
  cur = cur->next;


Snippet 2
---------
Lines 7-12: Your while loop is never going to execute because ptr is initialized to NULL.



Topic archived. No new replies allowed.