How to create simple singly linked list in C++

2 Answers

0 votes
#include <iostream> 

class LinkedListNode
{ 
private: 
    unsigned int m_Data = 0; 
    LinkedListNode* m_Next = nullptr; 
  
public: 
    LinkedListNode(unsigned int data) : m_Data{data} {} 
  
    int GetData() { 
        return m_Data; 
    } 

    void SetNext(LinkedListNode* next) { 
            m_Next = next; 
    } 
  
    LinkedListNode* GetNext() { 
        return m_Next; 
    } 
}; 

int main() {   
    LinkedListNode first(1); 
    LinkedListNode second(2); 
    LinkedListNode third(3); 
    LinkedListNode fourth(4); 
  
    first.SetNext(&second); 
    second.SetNext(&third); 
    third.SetNext(&fourth); 

    for (LinkedListNode* iter = &first; iter != nullptr; iter = iter->GetNext()) { 
        unsigned int number = (iter->GetData()); 
        std::cout << number << "\n"; 
    } 
}




/*
run:

1
2
3
4

*/

 



answered Feb 23, 2023 by avibootz
0 votes
#include <iostream>

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

class LinkedList
{
private:
    node *head, *tail;
public:
    LinkedList() {
        head = NULL;
        tail = NULL;
    }

    void AddNode(int n) {
        node *tmp = new node;
        tmp->data = n;
        tmp->next = NULL;

        if (head == NULL)  {
            head = tmp;
            tail = tmp;
        }
        else {
            tail->next = tmp;
            tail = tail->next;
        }
    }

    void Print() {
        node *tmp = head;
        while (tmp != NULL) {
            std::cout << tmp->data << "\n";
            tmp = tmp->next;
        }
    }
    
    void Delete() {
        node *tmp = head;
        while (tmp != NULL) {
            node *dl = tmp; 
            tmp = tmp->next;
            delete dl;
        }
    }
};

int main()
{
    LinkedList ll;
    
    ll.AddNode(1);
    ll.AddNode(2);
    ll.AddNode(3);
    
    ll.Print();
    
    ll.Delete();
}




/*
run:

1
2
3

*/

 



answered Feb 24, 2023 by avibootz

Related questions

...