Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Explanation
- This code implements a singly linked list in C++ and demonstrates inserting a node at the end:
- Node Structure: Holds an integer data and a pointer next to the next node.
- insertAtEnd Function:
- Creates a new node with the given data and sets its next to nullptr.
- If the list is empty (head is nullptr), sets the new node as the head.
- Otherwise, traverses from the head to the last node (where next is nullptr).
- Updates the last node's next to point to the new node.
- printList Function: Traverses and prints the list for verification.
- Main Function: Creates an empty list, inserts nodes (10, 20, 30), prints it, inserts 40 at the end, and prints again.
- Output:
- textLinked List before insertion: 10 -> 20 -> 30 -> NULL
- Linked List after insertion: 10 -> 20 -> 30 -> 40 -> NULL
- This matches the steps in the image: traverse to the last node, update its next from NULL to the new node, and set the new node's next to NULL.
- #include <iostream>
- // Define the Node structure
- struct Node {
- int data; // Data stored in the node
- Node* next; // Pointer to the next node
- };
- // Function to insert a new node at the end of the linked list
- void insertAtEnd(Node** head, int newData) {
- // Create a new node
- Node* newNode = new Node();
- newNode->data = newData;
- newNode->next = nullptr; // Next pointer of new node is NULL (end of list)
- // If the list is empty, the new node becomes the head
- if (*head == nullptr) {
- *head = newNode;
- return;
- }
- // Traverse to the last node
- Node* last = *head;
- while (last->next != nullptr) {
- last = last->next;
- }
- // Change the next pointer of the last node to the new node
- last->next = newNode;
- }
- // Helper function to print the linked list
- void printList(Node* head) {
- Node* temp = head;
- while (temp != nullptr) {
- std::cout << temp->data << " -> ";
- temp = temp->next;
- }
- std::cout << "NULL" << std::endl;
- }
- int main() {
- Node* head = nullptr; // Initialize empty list
- // Insert some nodes
- insertAtEnd(&head, 10);
- insertAtEnd(&head, 20);
- insertAtEnd(&head, 30);
- // Print the list before inserting new node
- std::cout << "Linked List before insertion: ";
- printList(head);
- // Insert a new node at the end
- insertAtEnd(&head, 40);
- // Print the list after insertion
- std::cout << "Linked List after insertion: ";
- printList(head);
- // Clean up memory (optional for this example, but good practice)
- Node* current = head;
- while (current != nullptr) {
- Node* next = current->next;
- delete current;
- current = next;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment