Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Linked List is a data structure that is made up of nodes that point to the next node in a sequence. To add and remove elements from a linked list using C++, you can follow these steps:

  1. Creating a Node Structure: First, create a node structure that will hold the data and a pointer to the next node.

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

  1. Creating a Linked List Class: Next, create a linked list class that will have functions to add, remove and display elements.

class LinkedList { private: Node* head; public: LinkedList() { head = NULL; } void addNode(int num); void deleteNode(int num); void displayList(); };

  1. Adding Nodes to the Linked List: To add a node to the linked list, create a new node and point its next to the head. Then, make the head point to the new node.

void LinkedList::addNode(int num) { Node* newnode = new Node; newnode->data = num; newnode->next = head; head = newnode; }

  1. Deleting Nodes from the Linked List: To delete a node from the linked list, find the previous node of the node to be deleted and point its next to the current node's next. Then, delete the current node.

void LinkedList::deleteNode(int num) { Node* prev = NULL; Node* curr = head; while(curr != NULL && curr->data != num) { prev = curr; curr = curr->next; } if(curr == NULL) { cout << "Data not found in the list.\n"; return; } if(prev == NULL) { head = curr->next; } else { prev->next = curr->next; } delete curr; }

  1. Displaying the Linked List: To display the linked list, traverse through each node and print its data.

void LinkedList::displayList() { Node* temp = head; while(temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; }

By following these steps, you can add and remove elements from a linked list using C++.