Legomert99
Legomert99

Reputation: 21

Creating a Linked List

So I have to crate a linked list for my project to add and multiply really big numbers. Bur I'm having a problem with creating a linked list. I have to get some output, but I cannot. And I cannot find a problem. It doesn't give an error, but also I cannot get any output as well. And I've compared with Linked List examples I could find, but still I cannot find the problem.

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

struct LLnode{
    int data;
    struct LLnode *next;
    LLnode (int);
};

LLnode::LLnode(int value){
    data = value;
    next = NULL;
}

class LinkedList{
private:
        LLnode *head, *tail, *temp;
public:
    LinkedList(){
        head = NULL;
        tail = NULL;
    }
    ~LinkedList();
    void createLLnode(int value);
    void display();
    void addToHead(int value);
    void deleteHead();
};

void LinkedList::createLLnode(int value){
    temp -> data = value;
    temp -> next = NULL;
    if(head == NULL){
        head = temp;
        tail = temp;
        temp = NULL;
    }
    else {
        tail -> next = temp;
        tail = temp;
    }
};

void LinkedList::display(){
    temp = head;
    while(temp != NULL){
        cout << temp->data << "\n";
        temp = temp -> next;
    }
};

void LinkedList::addToHead(int value){
    temp ->data = value;
    temp -> next = head;
    head = temp;
};

void LinkedList::deleteHead(){
    temp = head;
    head = head -> next;
    delete temp;
};

int main(){
    LinkedList* myList = new LinkedList();

    myList->createLLnode(8);
    myList->addToHead(12);
    myList->display();
    myList->deleteHead();
    myList->display();
    myList->addToHead(46);
    myList->addToHead(17);
    myList->display();

    return 0;
}

Upvotes: 0

Views: 96

Answers (1)

MorningDewd
MorningDewd

Reputation: 501

LLnode *head, *tail, *temp; are all pointers. This is fine for head and tail, but you seem to be using temp wrong, as you never allocate any memory for your nodes.

In the function void LinkedList::createLLnode(int value) you assign values to temp, but don't create a new object. The first line of the function should read

void LinkedList::createLLnode(int value) {
    temp = new LLnode;
    ...

In your LinkedList destructor you must then add code that iterates through your linked list and deletes all nodes.

Upvotes: 2

Related Questions