Linked List Operations
Linked List Operations
Here's a list of basic linked list operations that we will cover in this article.
struct node {
int data;
struct node *next;
};
Traverse a Linked List
Displaying the contents of a linked list is very simple. We keep moving the
temp node to the next one and display its contents.
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
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);
cout << "Linked list: ";
printList(head);
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);
}