I made a Linked-List with only an Insert Node function and a Print function, but It doesnt work.
#ifndef LIST_H_
#define LIST_H_
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
class List{
private:
Node* head;
public:
List(){
head = NULL;
}
void insertEnd(int d){
Node* newNode = new Node;
newNode->next = NULL;
newNode->data = d;
if (head == NULL){
head = newNode;
return;
}
Node* cu = head;
while (cu != NULL)
cu = cu->next;
cu->next = newNode;
}
void printList(){
Node* temp = new Node;
temp = head;
while (temp != NULL){
cout << temp->data << ", ";
temp = temp->next;
}
}
};
And my main function:
#include <iostream>
#include "List.h"
using namespace std;
int main(){
List list1;
list1.insertEnd(1);
list1.insertEnd(2);
list1.insertEnd(3);
//list1.printList();
return 0;
}
This program works if I only insert one node, but if I do anything else it crashes and doesn't give me any error indications or anything.
I've checked on several sites if my pointers were doing the right thing, and I think they are, but what is going wrong here...?
Edit: fixed the problem... in while loop should have been
while (cu->next != NULL)
bat, add apauseat the end so you can read the error.Node* cu = new Node; cu = head;- think this exist sense ?Node* temp = new Node; temp = head;this is c++ ?cu->next = newNode;afterwhile (cu != NULL)- so cu - always 0 here