Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- //struct for each separate node
- struct Node {
- int data;
- Node* next;
- //constructor
- Node(int value) {
- data = value;
- next = nullptr;
- }
- };
- //struct for the linked list
- struct LinkedList {
- Node* head;
- //constructor
- LinkedList() {
- head = nullptr;
- }
- void insert(int value) {
- Node* newNode = new Node(value);
- if (head == nullptr) {
- head = newNode; //create head node
- } else {
- Node* current = head;
- //while the next element in list exists
- while (current->next != nullptr) {
- current = current->next;
- }
- current->next = newNode; //updates the next pointer to the current node
- }
- }
- void display() {
- Node* current = head;
- while (current != nullptr) {
- std::cout << current->data << " -> ";
- current = current->next;
- }
- std::cout << "nullptr" << std::endl;
- }
- };
- int main()
- {
- LinkedList myList;
- int n;
- std::cout << "Enter the number of values to insert: ";
- std::cin >> n;
- for (int i = 0; i < n; i++) {
- int value;
- std::cout << "Enter a value: ";
- std::cin >> value;
- myList.insert(value); //Call the insert function
- }
- myList.display(); // Call the display function
- }
Advertisement
Add Comment
Please, Sign In to add comment