BlackWolfy

Linked List (insert, display)

Nov 2nd, 2023
628
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <iostream>
  2. //struct for each separate node
  3. struct Node {
  4.     int data;
  5.     Node* next;
  6.     //constructor
  7.     Node(int value) {  
  8.         data = value;
  9.         next = nullptr;
  10.     }
  11. };
  12. //struct for the linked list
  13. struct LinkedList {
  14.     Node* head;
  15.     //constructor
  16.     LinkedList() {
  17.         head = nullptr;  
  18.     }
  19.      void insert(int value) {
  20.         Node* newNode = new Node(value);
  21.         if (head == nullptr) {
  22.             head = newNode; //create head node
  23.         } else {
  24.             Node* current = head;
  25.             //while the next element in list exists
  26.             while (current->next != nullptr) {
  27.                 current = current->next;
  28.             }
  29.             current->next = newNode;    //updates the next pointer to the current node
  30.         }
  31.     }
  32.      void display() {
  33.          Node* current = head;
  34.          while (current != nullptr) {
  35.              std::cout << current->data << " -> ";
  36.              current = current->next;
  37.          }
  38.          std::cout << "nullptr" << std::endl;
  39.      }
  40. };
  41. int main()
  42. {
  43.     LinkedList myList;
  44.     int n;
  45.     std::cout << "Enter the number of values to insert: ";
  46.     std::cin >> n;
  47.  
  48.    for (int i = 0; i < n; i++) {
  49.         int value;
  50.         std::cout << "Enter a value: ";
  51.         std::cin >> value;
  52.         myList.insert(value); //Call the insert function
  53.     }
  54.     myList.display();   // Call the display function
  55. }
Advertisement
Add Comment
Please, Sign In to add comment