Unsorted Linked list in c++
To create an unsorted linked list in C++, follow these steps:
- Define a structure for the nodes of the linked list. Each node should contain a data element and a pointer to the next node in the list.
struct Node {
int data;
Node* next;
};
- Create a function to insert a new node at the beginning of the linked list. This function will take the data for the new node as a parameter.
void insertNode(Node head, int newData) {
Node* newNode = new Node();
newNode->data = newData;
newNode->next = *head;
*head = newNode;
}
- Create a function to display the contents of the linked list. This function will traverse the list and print the data of each node.
void displayList(Node* head) {
Node* currentNode = head;
while (currentNode != NULL) {
cout << currentNode->data << " ";
currentNode = currentNode->next;
}
}
- In the main function, create an empty linked list by initializing the head pointer to NULL.
int main() {
Node* head = NULL;
// Perform operations on the linked list
// ...
return 0;
}
- Use the
insertNode
function to add nodes to the linked list. For example, to insert a node with data 5 at the beginning of the list, callinsertNode(&head, 5)
.
insertNode(&head, 5);
- Use the
displayList
function to print the contents of the linked list.
displayList(head);
By following these steps, you can create an unsorted linked list in C++. Remember to deallocate the memory used by the linked list once you are done with it to avoid memory leaks.