Hi I have a problem with Sieve of Eratosthenes in C++. I have to do this using single linked list. My program is running and showing first declaration of list but I don't know how to delete non prime numbers properly. My function just isn't working for me. How should I change my delete function?
#include <iostream>
#include <cmath>
using namespace std;
struct List
{
int number;
List* next;
};
List* head = new List;
void l_add(int n)
{
List* temp = head;
for (int i = 2; i <= n; i++)
{
temp->next = new List();
temp->number = i;
temp = temp->next;
}
}
void l_print()
{
List* temp = head;
while (temp->next != 0)
{
cout << temp->number << " ";
temp = temp->next;
}
cout << endl;
}
void l_delete(int n)
{
List* temp = head;
for (int i = 2; i < sqrt(n); i++)
{
if (temp->number % i == 0)
{
head = temp->next;
delete temp;
temp = head;
}
while (temp->next != 0)
{
if (temp->next->number % i == 0)
{
temp->next = temp->next->next;
delete temp->next;
}
temp = temp->next;
}
}
}
int main()
{
int n;
cout << "Enter up to which number to find prime numbers using Sieve of Eratosthenes: " << endl;
cin >> n;
l_add(n);
l_print();
l_delete(n);
l_print();
return 0;
}
This would be a working version of the l_delete method:
void l_delete(int n)
{
List* temp = head;
for (int i = 2; i < sqrt(n); i++)
{
while (temp->next != 0)
{
if (temp->next->number % i == 0 && temp->next->number != i)
{
List* temp2 = temp->next->next;
delete temp->next;
temp->next = temp2;
}
if(temp->next == 0) break;
temp = temp->next;
}
temp = head;
if (temp->number % i == 0 && temp->number != i)
{
head = temp->next;
delete temp;
temp = head;
}
}
}
There were several problems with your deletion method.
Problems with algorithm logic: With your algorithm head should be checked last because otherwise if its deleted, the new head is not checked for primality, you immediately check new next, which is old ->next->next. Also you didn't check if number is equal to divider in which case it should not be deleted.
Problems with programming logic:
When you're deleting next node in the while loop, same as when deleting head, you need another temporary variable to store temp->next->next and then after deleting assign it to temp->next.
But the biggest problem here is that this is not Eratosthenes sieve at all, you are
just checking all numbers for divisibility with all others smaller than sqrt(n). It
is suboptimal compared to the Eratosthenes sieve. If you Google Eratosthenes sieve, you’ll find a lot of detailed tutorials and explanations.
I like what Bran is pitching, and I'm going to add a few tricks.
Comment: Global variables suck. They make things harder to trace when projects get bigger. I'd move head into main and pass it around as a parameter. I'm also ditching the sentry node because I find them more trouble than they are worth most of the time.
int main()
{
int n;
cout << "Enter up to which number to find prime numbers using Sieve of Eratosthenes: " << endl;
if (cin >> n)
{
// should be a bit more logic here to automatically handle ns of 1 or 2
List* head = nullptr; // not using a sentinel node
l_add(head, n); // passing in head rather than global variable free-for-all
l_delete(head);
l_print(head);
return 0;
}
else
{
cout << "invalid input." << endl;
return 1;
}
}
When adding to the linked list, you don't need any even numbers other than 2. So don't add them. Less time spent iterating the list. After that it's a matter of making sure nodes go in in the right order.
void l_add(List*& head, // passing in head. Easier to track
int n)
{
List** temp = &head; // head is a next pointer with a different name
// hiding it behind another pointer allows us to treat
// it like a next
// temp is now a pointer to next pointers. We can add directly to the
// last nodes's next pointer and also use it to access the current
// pointer if we need to
(*temp) = new List {2, nullptr}; // 2 is only even prime
temp = &(*temp)->next;
for (int i = 3; i <= n; i+=2) // start at 3 and only add odd numbers
{
(*temp) = new List {i, nullptr};
temp = &(*temp)->next; // Advance to next node
}
}
When we're iterating through the list looking to eliminate multiples we need two loops. One to keep track of the node we're eliminating multiples and another loop to do the hunting and eliminating. Note that I'm using the pointer-to-pointer trick again. This trick annihilates about half of the code needed to traverse and remove nodes.
void l_delete(List * head)
{
List* last = head->next; // track the last known prime node. skip node 2.
// note this will blow up if there is no node 2.
while (last) // for every node still in the list
{
List** current = &last->next; // similar to trick above.
// if we have a pointer to the next to be
// updated, we don't need to track the previous node
while ((*current)) // look at every node after the last prime
{
if ((*current)->number % last->number == 0) // if it's a multiple, remove it.
{
List * to_del = (*current); //save node to delete
(*current) = (*current)->next; // link previous node to next node.
// effectively automatically advances the node
delete to_del;
}
else // proceed to next node
{
current = &(*current)->next;
}
}
last = last->next; // advance to next prime number
}
}
Probably plenty of room in there for optimization, but I'm aiming more for readability because if I drop ten lines of cryptic gibberish nobody learns nuthin'.
Related
So basically I have this assignment on my University that asks to make a sorted singly linked list and then make some methods on it. The one that I'm having trouble is: "create delete() function that checks the average of each triple elements and if it's lower than integer 'K' (which is a parameter of said function) deletes the first element of the triple or deletes second and last element of the triple if it's higher."
I already made a function/method that deletes a single element of the linked list.
void LinkedList::deleteElement(int a)
{
Node *temp = head;
Node *previousTemp = head;
while(temp != nullptr)
{
if(temp->value == a)
{
break;
}
else
{
previousTemp = temp;
temp = temp->next;
}
}
if(temp == nullptr)
{
cout << "Can't delete. Element not found." << endl;
}
else
{
cout << "\nDeleting element: " << temp->value << endl;
previousTemp->next = temp->next;
delete temp;
}
howMany--;
}
void Sznur::deleteTriple()
{
Node *first = head;
Node *second = first->next;
Node *third = second->next;
}
The task is written pretty hard to understand but for ex.:
int K=3
linkedList: 7,6,6,3,3,3,2,1,1,1,1
after running the function:
linkedList: 7,3,1,1,1,1
(7+6+6)/3 > K -> deletes 6 and 6
(3+3+3)/3 > K -> deltes second 3 and last 3
(2+1+1)/3 < K -> deletes 2
If the linkedList length is not dividable by 3 the last elements stay in their place.
Try something like this.
void tripleFunc(Node* head, int K)
{
Node* nodePtr = head; // nodePtr always points at the start of a new triple
while (true)
{
Node* first = nullptr;
Node* second = nullptr;
Node* third = nullptr;
first = nodePtr; // When taking the three elements out, remember to always check for a null pointer BEFORE accessing the element
if (first)
second = first->next;
if (second)
third = second->next;
if (third)
nodePtr = third->next; // Keep the nodePtr pointing at the start of the next triple
else
return; // Only happens if one or more of the previous ifs failed, which means that we don't have enough elements left for a full triple
if (calculateAverage(first, second, third) < K) // Make this function
{
deleteElement(first->value);
}
else
{
deleteElement(second->value);
deleteElement(third->value);
}
}
}
I haven't tested it though, so any possible bugs are left as an exercise to the reader to find and sort out. :)
I am trying to delete the odd numbers that are randomly generated (see oddsOnly), and then print the list in reverse order. I can delete odds that may pop up at the beginning of the list, but I cannot find a way to delete anything after that.
I have tried various forms of if and while loops. Too many different ways for me to remember or list them all.
#include<iostream>
#include<ctime>
#include<fstream>
using namespace std;
struct Node
{
int element;
Node *next;
Node *previous;
};
// Function headers
int takeNumber(int);
int writeFile(int);
struct Node *readFile(Node *&, int);
void printBackward(Node *);
struct Node *oddsOnly(Node *&, int);
void deleteList(Node *);
// Main
int main(int argc, char *argv[])
{
// Check to see if the user passed us the size to make the list.
if (argc == 2)
{
// Check to see if what the user passed us is in fact a valid number.
// Here we attempt to assign what was passes in to us to an int variable
int Size = atoi(argv[1]);
// Now we check a few things. If the !Size tells us whether or not the
// assignment above was successful. If the size is less than 20 or
// greater than 100, the input did not follow the instructions. In
// either case we ask the user to enter another number with the printed
// instructions of it must be between 20 and 100.
if (!Size || Size < 20 || Size > 100)
{
Size = takeNumber(Size);
}
// Create the pointer for Head. This is used to keep track of the beginning
// of the list.
Node *Head = new Node;
if (Head == NULL)
{
cout << "fatal error: could not create Head node." << endl;
return(1);
}
Head = NULL;
// If we are here, the head node was created successfully. As this is
// currently also the last node in the list, set the pointer to NULL.
//Head->next = NULL;
writeFile(Size);
readFile(Head, Size);
// When you allocate memory with new or malloc, you should always clean
// free up the memory when you are through.
deleteList(Head);
}
else
{
int Size = 0;
Size = takeNumber(Size);
// Create the pointer for Head. This is used to keep track of the beginning
// of the list.
Node *Head = new Node;
if (Head == NULL)
{
cout << "fatal error: could not create Head node." << endl;
return(1);
}
Head = NULL;
// If we are here, the head node was created successfully. As this is
// currently also the last node in the list, set the pointer to NULL.
//Head->next = NULL;
writeFile(Size);
readFile(Head, Size);
oddsOnly(Head, Size);
// When you allocate memory with new or malloc, you should always clean
// free up the memory when you are through.
deleteList(Head);
}
system("pause");
return 0;
}
// Function to take input (size) from the user
int takeNumber(int Size)
{
while (Size < 20 || Size > 100)
{
// Output specific instructions to the user.
cout << endl << "Please inter a number between 20 and 100 (inclusive). " << endl;
// Take a given input from the user.
cin >> Size;
// Set a while loop so that if the incorrect input is given, the user will
// be asked to enter a different input untill it fits the given discription
// in the instructions.
if (cin.fail() || Size < 20 || Size > 100)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// Print error message and ask for another input.
cout << "Input is not between 20 and 100 (inclusive). " << endl;
cout << "Please try again. " << endl << endl;
}
}
// Return the input.
return Size;
}
// Function to write random numbers to a binary file
int writeFile(int size)
{
// Create and open the file you will write to.
ofstream WriteFile;
WriteFile.open("numbers.bin", ios::out | ios::binary);
// Make sure to print an error message if the file was not created.
if (!WriteFile)
{
cout << "Could not create/open binary file for writing. " << endl << endl;
return (1);
}
// Seed the random fuction with the time from the computer.
srand(int(time(NULL)));
// create a variable to store the random variable gernerated.
int number = 0;
// Create a loop to generate some random data and store it in
// the number variable. Then write the number to the to the binary
// file.
for (int i = 0; i < size; i++)
{
// Generate a random number between 0 and 99.
number = (rand() % 100);
// Write the number to the binary file.
WriteFile.write(reinterpret_cast<const char *>(&number), sizeof(int));
}
WriteFile << endl;
// Close the binary file.
WriteFile.close();
return(0);
}
// Function to read the binary file and create a linked list.
struct Node *readFile(Node *&Head, int Size)
{
// Create and open a read binary file
ifstream ReadFile;
ReadFile.open("numbers.bin", ios::in | ios::binary);
// Check to make sure file has been created and opened.
if (!ReadFile)
{
cout << "Could not open the binary file for reading. " << endl << endl;
}
int Data = 0;
int counter = 1;
while (ReadFile)
{
ReadFile.read((char*)&Data, sizeof(int));
if (ReadFile.eof())
{
break;
}
if (Head == NULL)
{
Node *tmp = new Node;
if (tmp == NULL)
{
cout << "fatal error: could not create tmp node" << endl;
}
tmp->element = Data;
tmp->next = NULL;
tmp->previous = NULL;
Head = tmp;
counter = counter + 1;
}
else if (Head != NULL)
{
Node *current = new Node;
if (current == NULL)
{
cout << "fatal error: could not create current node" << endl;
}
current = Head;
while (current->next != NULL)
{
current = current->next;
}
struct Node *temp = new Node;
if (temp == NULL)
{
cout << "fatal error: could not create temp node" << endl;
}
temp->element = Data;
temp->next = NULL;
temp->previous = current;
current->next = temp;
counter = counter + 1;
}
}
cout << endl;
// Close the file
ReadFile.close();
oddsOnly(Head, Size);
printBackward(Head);
cout << endl;
return Head;
}
// Function to read the numbers.bin file and put numbers in reverse order
void printBackward(Node *Head)
{
// We now have a list. We can traverse the list and print the elements.
// We have the head, we create a current or tmp node pointer to set it
// equal to head.
Node *temp;
temp = Head;
while (temp->next != NULL)
{
temp = temp->next;
}
// We can use a counter to format the output on the console
int counter = 1;
// This is our loop to traverse the list. We start at head, and go until
// we reach the null pointer of the last node.
while (temp != NULL)
{
// This prints the number in the node, then a tab separator to the
// console.
cout << temp->element << "\t";
// This is used for formatting the output on the screen. In this case,
// after every five nodes have been printed, we insert a newline and
// reset the counter to 0.
if (counter % 5 == 0)
{
cout << endl;
counter = 0;
}
// We advance the tmp or current pointer to the next value and increment the counter.
temp = temp->previous;
counter = counter + 1;
}
}
// Function to weed out the odd numbers in the list
struct Node *oddsOnly(Node *&Head, int size)
{
int counter = 1;
while (Head->element % 2 == 0)
{
struct Node *temp = Head;
Head = Head->next;
Head->previous = NULL;
delete(temp);
return Head;
counter = counter + 1;
}
Node *tmp = Head;
while (tmp != NULL)
{
Node *current = Head;
while (current->element % 2 != 0 && current->next->next != NULL)
{
current = current->next;
tmp = current->next;
}
current->previous->next = current->next;
current->next->previous = current->previous;
delete(current);
struct Node *current1 = Head;
while (current1->next != NULL)
{
current1 = current1->next;
}
if (current1->element % 2 == 0)
{
current1->previous->next = NULL;
delete(current1);
}
tmp = tmp->next;
}
cout << endl;
return Head;
}
// Function to delete the link list.
void deleteList(Node *Head)
{
Node *tmp;
// Loop through the list, deleting one node at a time. We set tmp equal
// to the node after head, delete head and then set head equal to tmp.
while (Head != NULL)
{
tmp = Head->next;
delete(Head);
Head = tmp;
}
}
I am looking for a list that allows 5 integers before starting a new line, and that has only odd values from the linked list.
I have gotten a lot of error messages displaying 0xDDDDDDDD in the oddsOnly function. at this point though, I am only seeing that it is not deleting the evens after the first node in the list.
Refer to the following diagram:
To delete node B from the list, set A.Next to A.Next.Next, set C.Prev to C.Prev.Prev, and free node B.
To delete node D from the list, set C.Next to C.Next.Next (which is null), and free node D.
Make sure you write a function that does this. Your code suggests that you're not fully taking advantage of the encapsulation and "divide and conquer" strategy that functions provide.
Further Reading
Delete a node in a Doubly Linked List
Stealing Roberts great picture
I don't quite agree with his description (it is correct though just a bit complicated when written in English).
Node* x = findNodeToDelete();
if (x == nullptr) { // Check to make sure you have an actual node to delete.
return;
}
if (x->next != nullptr) {
x->next->prev = x->prev;
}
if (x->prev != nullptr) {
x->prev->next = x->next;
}
else {
Head = x->next;
}
// Now you have unlinked the node from the list.
x->next = nullptr; // Optional if node has a complex destructor may be worth it.
x->prev = nullptr; // Optional
// Now release the node you are deleting.
delete x;
As you know there are 3 situations in deleting being
1 - head
2 - middle
3- end
I think you covered the first one lest proceed to the second one
lets say you are in a traversing loop
while( cur != NULL ){
...
cur = cur -> next;
let's look at the middle of the node for second case
For deletion in the middle, you should know the previous node and the next node of to deleted node and you should bind them together. Luckily you both have previous and next in doubly linked list.
so lets add a statement to a code
if ( cur -> data == oddNumber ){
Node* prev = cur -> prev;
Node* next = cur -> next;
prev -> next = cur -> next;
delete cur;
cur = cur -> next;
}
that was for the middle, and for the end (3 rd case) you can simply check if the next node of the node is NULL and delete it peacefully.
#include <iostream>
#include <memory>
using namespace std;
struct Node
{
int data;
Node* next;
};
void append(Node*&, int);
void printList(Node*);
void insertNode(Node*&, int, int);
void searchList(Node*, int, int);
int main()
{
Node* head = nullptr;
int initialCount = -1, userInput, newNodeLoc = -1, newNodeVal, searchVal;
/// INITIALIZE LIST
while(initialCount <= 0)
{
cout<<"Enter the number of initial nodes (must be at least 1): ";
cin>>initialCount;
}
cout<<endl;
for(int i = 0;i<initialCount;i++)
{
cout<<"Enter a number: ";
cin>>userInput;
append(head,userInput);
}
cout<<endl;
cout<<"Here are the initial values in the linked list: "<<endl;
printList(head);
cout<<"\nEnter a number for a new node to insert to the linked list: ";
cin>>newNodeVal;
cout<<endl;
cout<<"Enter which position you want to insert it (ex. "<<head->data<<" is at pos 1): ";
cin>>newNodeLoc;
while((newNodeLoc<=0 || newNodeLoc>initialCount))
{
cout<<"New position must be greater than 1 and less than " << initialCount+1 <<": ";
cin>>newNodeLoc;
}
newNodeLoc--;
insertNode(head, newNodeVal, newNodeLoc);
cout<<"\nHere is the updated linked list: "<<endl;
printList(head);
/// SEARCH
cout<<"\nEnter the number that you want to search for in the list: ";
cin>>searchVal;
cout<<endl;
initialCount++;
cout<<initialCount;
searchList(head,searchVal,initialCount);
return 0;
}
void printList(Node* head)
{
Node *n = head;
cout<<n->data<<endl;
while(n->next != nullptr) // print out all nodes values'
{
cout << n->next->data<<endl;
n = n->next;
}
}
void append(Node*& head, int val)
{
Node* temp = new Node;
temp->data = val;
temp->next = nullptr;
Node* ptr = head;
if(head == nullptr) // check if list is empty
{
head = temp;
}
else
{
while(ptr->next != nullptr) // if list isn't empty, get to last element set it equal to temp
{
ptr = ptr->next;
}
if(ptr->next == nullptr)
{
ptr->next = temp;
}
}
delete temp;
temp = nullptr;
}
void insertNode(Node*& head, int val, int loc)
{
Node* temp = new Node;
Node* prevLoc = new Node;
Node* curr = head;
temp->data = val;
int tempPos = 0;
while(curr->next != nullptr && tempPos != loc)
{
prevLoc = curr;
curr = curr->next;
tempPos++;
}
prevLoc->next = temp;
temp->next = curr;
delete temp;
delete prevLoc;
curr = nullptr;
prevLoc = nullptr;
}
void searchList(Node* head, int sVal, int iCount)
{
Node* curr = head;
int index=0;
while(curr->next != nullptr && curr->next->data != sVal)
{
curr = curr->next;
index++;
}
cout<<index;
cout<<iCount;
if(index != iCount)
{
cout<<"Number found at index "<<index<<" in the linked list!";
}
if(index-1 == iCount)
cout<<"Number could not be found in this linked list.";
delete curr;
curr = nullptr;
}
Hi there! I'm trying to implement append/prntlist/insertnode/search functions and I'm getting extremely inconsistent compiling results. Sometimes the code will run fine. Sometimes the code will randomly break. Other times it'll print out numbers on an infinite loop. I'm thinking it's a memory leak somewhere (in append/print functions), but I'm not super confident. It might also be a loop that's breaking the code. Any and all help is appreciated! I understand that the search function doesn't work so you can ignore it. Thank you!
In your append():
delete temp;
temp is your new element, that you've just append()ed to the list. Now that it's a part of the list, it gets immediately deleted. Good-bye!
The next to the last element of your linked list now points to deleted memory. Subsequent attempt to walk the list results in undefined behavior. Subsequent attempts to append more elements to the list will just make things even worse, scribbling over deleteed memory (if it wasn't scribbled over anyway, by the next new) and generally making a major mess of everything.
The memory allocation logic in insert() is similarly flawed. It's even worse. Two news and two deletes. Furthermore, the overall logic is also wrong. Its ostensible purpose is to insert one more element to the list, so it shouldn't be allocating two new nodes, only one will do. Both append() and insert() add one more node to the list; so only one node needs to be newed in both cases.
But the overall problem is erroneous deletions of newed elements, when they should not be newed, and they continue to be used. You cannot use anything after it gets deleted. It's gone. It ceased to exist. It joined the choir-invisible. It's an ex-object. But the shown code erroneously deletes an element after it gets added to the link list and, ostensibly, is still logically a part of the link list.
I have a problem, I am trying to create a list that deletes a highest value holding number, or all numbers with the same value if the value is highest in the list. Thank you for any kind of tips.
// n,n1,head,next - are pointers
int j = 0; //this number helps to put pointer forward by one place
while(n!=0){//should go through every digit of the list
if(head == 0){
cout << "list is empty" << endl;
}
else{
n = head;
n1=0; // n1 and n are pointers
while(n!=0){
if(n->sk == maxx){//searches for maximum digit in the list
break;
}
else{
n1=n;
n=n->next;
}
}
if(head == n){
head = head->next;
}
else{
n1->next = n->next;
}
delete n; // deletes the pointer holding the highest value
}
n = head; //problem is here or somewhere below
j++;
for(int i=0; i<j;i++){ // this loop should make the pointer point to the first
n = n->next; // number, then the second and so on until the end of list
} // and all the numbers inside the list with the value that
} // equals "maxx" should be deleted
You should dereference the pointers. Right now, you're pointing to their addresses. See if that helps resolve your problem.
Ok, the problem (the most of it) is the code:
while(n!=0){
if(n->sk == maxx){
break;
}
else{
n1=n;
n=n->next;
}
}
If you find the maxx value you should delete that node and continue to searching, don't break. This way you don't need so much code for this task.
while (n != 0){
if (n->sk == maxx){
node *prev = n->prev; // The previous node.
node *tmp = n; // this assume you have a class node.
// temporaly holds the pointer to n.
prev->next = n->next; // Connect the previous node with the following one.
n = n->next; // advance n to the next node in the list.
delete tmp; // delete the node.
}
}
If I understand correctly what you want, you can just iterate over your list and save the pointer for deletion:
it = head;
pos = nullptr;
while (it != nullptr) {
if(it -> sk == maxx) {
pos = it; // save ptr
it = it -> next;
delete pos; // delete saved ptr
pos = nullptr;
}
}
So, in my linked list program, what I want it to do is to ask the user how many numbers to input, and enter the numbers, and add those numbers at the end of the list. Then, it will print the list. After that, the user will choose a position of element in the list to delete and the list will be printed again.
#include <iostream>
using namespace std;
struct Node{
int data;
Node* link;
};
Node* head;
void Insert(int data){ //insert an integer at the end of the list
Node* temp = new Node();
Node* temp2 = new Node();
temp->data = data;
temp->link = NULL;
if(head = NULL){
head = temp;
return;
}
temp2 = head;
while(temp2->link != NULL){
temp2 = temp2->link;
}
temp2->link = temp;
}
void Delete(int n){ //delete an integer at nth position
Node* temp1 = new Node();
temp1 = head;
if(n == 1){ //if the first node is to be deleted
head = temp1->link; //now head points to second node
delete temp1; //delete first node
return;
}
for(int i = 0; i < n-2; i++){
temp1 = temp1->link; //temp1 points to (n-1)th node
}
Node* temp2 = temp1->link; //temp2 points to nth node
temp1->link = temp2->link; // pointing to (n+1)th node
delete temp2; //deleting nth node
}
void Print(){ //print out the list
Node* printNode = head;
cout << "List: ";
while(printNode != NULL){
cout << printNode->data;
cout << " ";
printNode = printNode->link;
}
cout << "\n";
}
int main(){
int x, count, n;
head = NULL; //start with an empty list
cout << "How many numbers? " << endl;
cin >> count;
for(int i = 0; i < count; i++){
cout << "Enter number: ";
cin >> x;
Insert(x);
}
Print();
cout << "Enter position to delete: ";
cin >> n;
Delete(n);
Print();
return 0;
}
After accepting the first number, the program stops working. Can I know where I did the code wrong and what can I do to make this code more efficient? Thanks in advance.
Big facepalm on my part, only a small mistake. Code has been corrected.
if(head == NULL){
head = temp;
return;
}
You might need to rethink your insertion function. The part that your code crashes on is during the while loop insertion. If you want temp2 to hold data then you need to dynamically allocate space for it which you did. However, you are just using it as a position indicator (to traverse the list) - so why do you need to allocate space just to point to head or any other nodes location in your list?
Here's how I would insert into the list (at the back of course):
void Insert(int data){ //insert an integer at the end of the list
Node* temp = new Node();
// This is to ensure that temp was created -> Also called defensive programming.
if (!temp)
{
cout << "We did not have enough space alloted to dynamically allocate a node!" << endl;
exit(1);
}
temp->data = data; // Bad nominclature for program; Don't use the same name twice.
temp->link = NULL;
if (head == NULL)
{
head = temp;
}
else
{
// This is to help traverse the linked list without having to
// manipulate the position of what head points to.
Node *Pos_Indicator = head;
while (Pos_Indicator->link != NULL)
{
Pos_Indicator = Pos_Indicator->link;
}
// We are at the end of the list, it is now safe to add.
Pos_Indicator->link = temp;
// Should probably have a check here for whether it was successful or not.
}
}
I was able to compile and run your code to completion with no other problems. Let me know if this helps!
EDIT: or you know (head = NULL) to (head == NULL) works too :(