C++ Linked List Operations
C++ Linked List Operations
C++ Linked List Operations
There are various linked list operations that allow us to perform different
actions on linked lists. For example, the insertion operation adds a new
element to the linked list.
Here's a list of basic linked list operations that we will cover in this article.
struct node {
int data;
struct node *next;
};
When temp is NULL , we know that we have reached the end of the linked list
so we get out of the while loop.
• Store data
• Store data
temp->next = newNode;
head = head->next;
temp->next = temp->next->next;
• In each iteration, check if the key of the node is equal to item . If it the
key matches the item, return true otherwise return false .
// Search a node
bool searchNode(struct Node** head_ref, int key) {
struct Node* current = *head_ref;
6. Check if the data of the current node is greater than the next node. If
it is greater, swap current and index .
Check the article on bubble sort for better understanding of its working.
if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
// index points to the node next to current
index = current->next;
#include <stdlib.h>
#include <iostream>
using namespace std;
// Create a node
struct Node {
int data;
struct Node* next;
};
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
last->next = new_node;
return;
}
// Delete a node
void deleteNode(struct Node** head_ref, int key) {
struct Node *temp = *head_ref, *prev;
free(temp);
}
// Search a node
bool searchNode(struct Node** head_ref, int key) {
struct Node* current = *head_ref;
if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
// index points to the node next to current
index = current->next;
// Driver program
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);
int item_to_find = 3;
if (searchNode(&head, item_to_find)) {
cout << endl << item_to_find << " is found";
} else {
cout << endl << item_to_find << " is not found";
}
sortLinkedList(&head);
cout << "\nSorted List: ";
printList(head);
}