简体   繁体   中英

Specify insertion or append to linked list in c++

I want to ensure before I add the value to the linked list if the number is odd I want to add it to head (my alias is left) if else I want to add it to the last(my alias is right) here is my code The Node struct

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

The Linked List class

class LinkedList{
    Node *left;
    Node *right;
    
    public:
        LinkedList(){
            left = NULL;
            right = NULL;
        };
    void insert(int value)
    {
        Node *t = new Node();
        t->data = value;

        t->next = left;
        
        left = t;
        
        if(right == NULL)
            right = t;
    }
    void append(int value)
    {
        Node *temp = new Node();
        temp->data = value;
        
        temp->next = NULL;
        
        right = temp;
        
        if(left == NULL)
            left = temp;
    }
    void add(int  value){
        if(value % 2 == 0)
            append(value);
        else
            insert(value);
    }
    void print(){
    Node *node = left;
        while(node != NULL)
        {
            cout << node->data << " ";
            node = node->next;
        }
    }
};

in main method

LinkedList list = LinkedList();
    list.add(9);
    list.add(16);
    list.add(12);
    list.add(12);
    list.add(7);
    list.print();

but the out put is:

12 12 16 9

You're forgetting to link the last (rightmost) node to your new node in append() . Before you update right , you need to add:

if(right != nullptr) { right->next = temp; }

So it'll become:

void append(int value)
{
    Node *temp = new Node();
    temp->data = value;
    temp->next = NULL;

    if(right != nullptr) { right->next = temp; } 
    right = temp;
    
    if(left == NULL)
        left = temp;
}

Also don't forget your destructor/copy constructor/assignment operator to ensure you're being safe with your allocated memory!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM