Strange behaviour when I am trying to implement my linked list in c++

  c++, data-structures, singly-linked-list

I’m trying to implement my singly linked list , and I have this problem:

When I’m trying to pushBack some elements in my linked list , it will print only the first one which I added.For example , if I try to pushBack 2,3,4 – it will print only 2.

In case if I want to pushUp some elements in my linked list , it will print only the third one which I added. For example , if I try to pushUp 2,3,4 – it will print only 4.

This is my code:

enter code here

#include<iostream>
#include<vector>
using namespace std;

struct Node {
   int data;
   Node* next;
};

class LinkedList {
private:
    // Create pointers for head and tail
    Node *head , *tail;

public:
    LinkedList(){
        // Initiate them as null pointers
        head = NULL;
        tail = NULL;
    }

public:
    void pushBack(int value){
        // Should add a node at the end of the linked list
        
        Node* temp = new Node(); // temporary node which should be added
        temp->data = value; // value to store
        temp->next = NULL; // pointer to the next node

        if(head != NULL){
            // If there are some elements , then 
            temp->next = tail->next;
            tail = temp;
        }

        if(head == NULL){
            // If there are no elements , our node will be a head and a tail in the same time.
            head = temp; 
            tail = temp;
        }

    }

    void pushUp(int value){
        // Shound add a node at the beginning of the linked list
       Node* temp = new Node();
       temp->data = value;
       temp->next = NULL;

       if(head == NULL){
           // If there are no elements , our node will be a head and a tail in the same time.
           head = temp;
           tail = temp;
       }

       if(head != NULL){
           // If there are some elements , just make our node to be new head.
           temp->next = head->next;
           head = temp;
       }
    }

    void traversal(){
        Node *temp = new Node();
        temp = head;

        while(temp != NULL){
            cout << temp->data << " ";
            temp = temp->next;
        }
    }
 };


int main(){
// Pointer for our first node.
LinkedList a;

a.pushUp(2);
a.pushUp(124);
a.pushUp(3);

// a.pushBack(2);
// a.pushBack(124);
// a.pushBack(3); // Outputs only 2

a.traversal();  // Outputs only 3
}

Source: Windows Questions C++

LEAVE A COMMENT