0% found this document useful (0 votes)
13 views

Linked Lists Programs

Uploaded by

shagun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Linked Lists Programs

Uploaded by

shagun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

1.

Insert a Node at the Front/Beginning of Linked List


To insert a new node at the front, we create a new node and point
its next reference to the current head of the linked list. Then, we update
the head to be this new node. This operation is efficient because it only
requires adjusting a few pointers.
Insert a Node at the Front/Beginning of Linked List

To insert a node at the front of the linked list, follow these steps:
 Create a new node.
 Set the next pointer of the new node to the current head of the list.
 Update the head pointer to the new node.
Below is the implementation of the approach:

C++
// C++ Program to insert the node at the beginning of
// Linked List
#include <bits/stdc++.h>
using namespace std;

struct Node {

int data;
Node* next;

Node(int new_data)
{
data = new_data;
next = nullptr;
}
};

// Function to insert a new node at the beginning of the


// list
Node* insertAtFront(Node* head, int new_data)
{
// Create a new node with the given data
Node* new_node = new Node(new_data);

// Make the next of the new node point to the current


// head
new_node->next = head;

// Return the new node as the new head of the list


return new_node;
}

void printList(Node* head)


{
Node* curr = head;
while (curr != nullptr) {
cout << " " << curr->data;
curr = curr->next;
}
cout << endl;
}

int main()
{
// Create the linked list 2->3->4->5
Node* head = new Node(2);
head->next = new Node(3);
head->next->next = new Node(4);
head->next->next->next = new Node(5);

// Print the original list


cout << "Original Linked List:";
printList(head);

// Insert a new node at the front of the list


cout << "After inserting Nodes at the front:";
int data = 1;
head = insertAtFront(head, data);

// Print the updated list


printList(head);

return 0;
}

Output
Original Linked List: 2 3 4 5
After inserting Nodes at the front: 1 2 3 4 5
Time Complexity: O(1), We have a pointer to the head and we can
directly attach a node and update the head pointer. So, the Time
complexity of inserting a node at the head position is O(1).
Auxiliary Space: O(1)
2. Insert a Node after a Given Node in Linked List
If we want to insert a new node after a specific node, we first locate that
node. Once we find it, we set the new node’s next reference to point to
the node that follows the given node. Then, we update the given node’s
next to point to the new node. This requires traversing the list to find the
specified node.

Insertion after a given node in Linked List

To insert a node after a specific node:


 Traverse the list to find the node after which you want to insert the new
node.
 Create a new node.
 Set the next pointer of the new node to the next pointer of the given
node.
 Update the next pointer of the given node to the new node.
Below is the implementation of the approach:
C++
// C++ Program to Insert a Node after a Given Node in Linked
// List
#include <bits/stdc++.h>
using namespace std;

struct Node {
int data;
Node* next;
Node(int value)
{
data = value;
next = nullptr;
}
};

// Function to insert a new node after a given node


Node* insertAfter(Node* head, int key, int newData)
{
// Initilize curr Pointer to head
Node* curr = head;

// Iterate over Linked List to find the key


while (curr != nullptr) {
if (curr->data == key)
break;
curr = curr->next;
}

// if curr becomes NULL means, given key is not


// found in linked list
if (curr == nullptr)
return head;

// Allocate new node by given data and point


// the next of newNode to curr's next &
// point current next to newNode
Node* newNode = new Node(newData);
newNode->next = curr->next;
curr->next = newNode;
return head;
}

void printList(Node* node)


{
while (node != nullptr) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}

int main()
{
// Create the linked list 2->3->4->5
Node* head = new Node(2);
head->next = new Node(3);
head->next->next = new Node(5);
head->next->next->next = new Node(6);

cout << "Original Linked List: ";


printList(head);

// Key: Insert node after key


int key = 3, newData = 4;

// Insert a new node with data 4 after the node having


// data 3
head = insertAfter(head, key, newData);
cout << "Linked List after insertion: ";
printList(head);

return 0;
}

Output
Original Linked List: 2 3 5 6
Linked List after insertion: 2 3 4 5 6
Time complexity: O(N), where N is the number of nodes in the linked list.
Since there is a loop from head to end, the function does O(n) work.
Auxiliary Space: O(1)
3. Insert a Node At a Specific Position in Linked List
To insert a new node at a specific position, we need to traverse the list to
position – 1. If the position is valid, we adjust the pointers similarly such
that the next pointer of the new node points to the next of current
nod and next pointer of current node points to the new node.

Insertion at specific position in Linked List

To insert a node at a specific position:


 Traverse the list to the position where you want to insert the new node.
 Create a new node.
 Adjust the next pointers to insert the new node at the desired position.
Below is the implementation of the approach:
C++
// C++ Program to Insert a Node At a Specific Position in
// Linked List
#include <iostream>
using namespace std;

struct Node {
int data;
Node* next;
Node(int data)
{
this->data = data;
this->next = nullptr;
}
};

// Function to insert a node at a specific position in the


// linked list.
Node* insertAtPosition(Node* head, int position, int data)
{
Node* newNode = new Node(data);

// If inserting at the beginning


if (position == 1) {
newNode->next = head;
head = newNode;
return head;
}

Node* current = head;


// Traverse the list to find the node before the
// insertion point
for (int i = 1; i < position - 1 && current != nullptr;
++i) {
current = current->next;
}

// If the position is out of bounds


if (current == nullptr) {
cout << "Position is out of bounds." << endl;
delete newNode; // Deallocate memory to prevent
// memory leak
return head;
}

// Insert the new node at the specified position


newNode->next = current->next;
current->next = newNode;
return head;
}

void printList(Node* head)


{
while (head != nullptr) {
cout << " " << head->data;
head = head->next;
}
cout << endl;
}

int main()
{
// Creating the list 3->5->8->10
Node* head = new Node(3);
head->next = new Node(5);
head->next->next = new Node(8);
head->next->next->next = new Node(10);

cout << "Linked list before insertion:";


printList(head);

// Insert a new node with data 12 at position 3


int data = 12, pos = 2;
head = insertAtPosition(head, pos, data);
cout << "Linked list after insertion of 12 at position "
"3:";
printList(head);

return 0;
}

Output
Linked list before insertion: 3 5 8 10
Linked list after insertion of 12 at position 3: 3 12 5 8 10
Time complexity: O(N), where N is the number of nodes in the linked list.
Since there is a loop from head to end, the function does O(n) work.
Auxiliary Space: O(1)
4. Insert a Node at the End of Linked List
Inserting at the end involves traversing the entire list until we reach the
last node. We then set the last node’s next reference to point to the new
node, making the new node the last element in the list.

Insertion at end of Linked List

To insert a node at the end of the linked list:


 Traverse the list to reach the last node.
 Create a new node.
 Set the next pointer of the last node to the new node.
Below is the implementation of the approach:
C++
// C++ Program to Insert a Node at the End of Linked List
#include <iostream>
using namespace std;

class Node {
public:
int data;
Node* next;

Node(int new_data)
{
data = new_data;
next = nullptr;
}
};

// Function appends a new node at the end and returns the


// head.
Node* insertAtEnd(Node* head, int new_data)
{
// Create a new node
Node* new_node = new Node(new_data);

// If the Linked List is empty, make


// the new node as the head and return
if (head == nullptr) {
return new_node;
}

// Store the head reference in a temporary variable


Node* last = head;

// Traverse till the last node


while (last->next != nullptr) {
last = last->next;
}

// Change the next pointer of the last node


// to point to the new node
last->next = new_node;

// Return the head of the list


return head;
}

void printList(Node* node)


{
while (node != nullptr) {
cout << node->data << " ";
node = node->next;
}
}

int main()
{
// Create a linked list: 2->3->4->5->6
Node* head = new Node(2);
head->next = new Node(3);
head->next->next = new Node(4);
head->next->next->next = new Node(5);
head->next->next->next->next = new Node(6);

cout << "Created Linked list is: ";


printList(head);

// Example of appending a node at the end


head = insertAtEnd(head, 1);

cout << "\nAfter inserting 1 at the end: ";


printList(head);

return 0;
}

Output
Created Linked list is: 2 3 4 5 6
After inserting 1 at the end: 2 3 4 5 6 1
Time complexity: O(N), where N is the number of nodes in the linked list.
Since there is a loop from head to end, the function does O(n) work.
Auxiliary Space: O(1)
1. Delete the Head Node
When deleting the head node, we need to adjust the head pointer to point
to the next node otherwise, the whole linked list can be lost.
Following is the approach to remove the head node of the linked list:
 Store the current head node in a temporary variable.
 Move the head pointer to the next node.
 Delete the temporary node.
Implementation
C++

// C++ program to show how to delete a head node from


// the linked list
#include <iostream>
using namespace std;

class Node {
public:
int data;
Node *next;
Node(int data) {
this->data = data;
this->next = nullptr;
}
};

// Function to delete the head node


void deleteHead(Node *&head) {
if (head == nullptr) {
cout << "List is empty, nothing to delete." << endl;
return;
}

// Store current head in a temporary variable


Node *temp = head;

// Move head to the next node


head = head->next;

// Delete the old head node


delete temp;
}
int main() {

// Create a simple linked list: 3 -> 12 -> 15 -> 18


Node *head = new Node(3);
head->next = new Node(12);
head->next->next = new Node(15);
head->next->next->next = new Node(18);

cout << "Original List: ";


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

deleteHead(head); // Deleting the head node

cout << "List after deleting head: ";


temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;

return 0;
}

Output
Original List: 3 -> 12 -> 15 -> 18 -> NULL
List after deleting head: 12 -> 15 -> 18 -> NULL
Time Complexity: O(1)
Auxiliary Space: O(1)
2. Delete the Tail Node
To delete the tail node, traverse the list to find the second-to-last node,
and then set its next pointer to NULL.
Following is the approach to remove the head node of the linked list:
 Traverse the list to find the second-to-last node.
 Set the next pointer of the second-to-last node to NULL.
 Delete the last node.
Implementation
C++

// C++ program to show how to delete a head node from


// the linked list
#include <iostream>
using namespace std;

class Node {
public:
int data;
Node *next;
Node(int data) {
this->data = data;
this->next = nullptr;
}
};

void deleteTail(Node*& head) {

// Check if the list is empty


if (head == nullptr) {
cout << "List is empty, nothing to delete." << endl;
return;
}

// Check if it contains only one element


if (head->next == nullptr) {
delete head;
head = nullptr;
return;
}

// Traverse to the tail node


Node* temp = head;
while (temp->next->next != nullptr) {
temp = temp->next;
}

// delete the tail node


delete temp->next;
temp->next = nullptr;
}

int main() {

// Create a simple linked list: 3 -> 12 -> 15 -> 18


Node *head = new Node(3);
head->next = new Node(12);
head->next->next = new Node(15);
head->next->next->next = new Node(18);
cout << "Original List: ";
Node *temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;

deleteTail(head); // Deleting the tail node

cout << "List after deleting head: ";


temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;

return 0;
}

Output
Original List: 3 -> 12 -> 15 -> 18 -> NULL
List after deleting head: 3 -> 12 -> 15 -> NULL
Time Complexity: O(N), where N is the number of nodes in the list.
Auxiliary Space: O (1)
3. Delete a Node at a Specific Position
To delete a node at a specific position, traverse the list to reach the node
just before the target position, adjust pointers to skip the target node, and
delete it.
Following is the approach to remove the head node of the linked list:
 If the position is 1, delete the head. Otherwise,
 Traverse the list to reach the node before the target position.
 Adjust pointers to bypass the target node and point to then next of the
target node.
 Delete the target node.

Implementation
C++

// C++ program to show how to delete a head node from


// the linked list
#include <iostream>
using namespace std;

class Node {
public:
int data;
Node *next;
Node(int data) {
this->data = data;
this->next = nullptr;
}
};

// Function to delete a node at a specific position


void deleteAtPosition(Node*& head, int pos) {
if (head == nullptr || pos < 1) {
cout << "Invalid position or list is empty." << endl;
return;
}

// Deleting head node


if (pos == 1) {
Node* temp = head;
head = head->next;
delete temp;
return;
}

// Traverse to the node before the target position


Node* current = head;
for (int i = 1; i < pos - 1 && current != nullptr; i++) {
current = current->next;
}

// If position is greater than the number of nodes


if (current == nullptr || current->next == nullptr) {
cout << "Position exceeds list length." << endl;
return;
}

// Delete the node at the target position


Node* temp = current->next;
current->next = temp->next;
delete temp;
}

int main() {

// Create a simple linked list: 3 -> 12 -> 15 -> 18


Node *head = new Node(3);
head->next = new Node(12);
head->next->next = new Node(15);
head->next->next->next = new Node(18);
cout << "Original List: ";
Node *temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;

deleteAtPosition(head, 2); // Deleting node at position 3

cout << "List after deleting head: ";


temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;

return 0;
}

Output
Original List: 3 -> 12 -> 15 -> 18 -> NULL
List after deleting head: 3 -> 15 -> 18 -> NULL
Time Complexity: O(N), where N is the number of nodes in the list.
Auxiliary Space: O (1)
Conclusion
Deleting a node from a linked list is a common operation that requires
careful handling of pointers to avoid breaking the list structure. Depending
on the position of the node to be deleted (head, tail, or a specific position),
the approach varies slightly. These examples demonstrate how to handle
different deletion scenarios in a singly linked list effectively.

MENU DRIVEN PROGRAM

Here's a C++ program that implements a menu-driven system to maintain a linear linked list
with elements stored in ascending order. The program includes separate functions for
inserting, deleting, searching, and displaying the elements of the list.

#include <iostream>
using namespace std;

// Node structure for the linked list


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

// Function to create a new node


Node* createNode(int data) {
Node* newNode = new Node();
if (!newNode) {
cout << "Memory error\n";
return nullptr;
}
newNode->data = data;
newNode->next = nullptr;
return newNode;
}

// Function to insert a new element in ascending order


void insertElement(Node*& head, int data) {
Node* newNode = createNode(data);
if (!newNode) return;

if (!head || head->data >= data) { // Insert at the beginning


newNode->next = head;
head = newNode;
} else {
Node* current = head;
while (current->next && current->next->data < data) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
cout << "Element inserted successfully.\n";
}

// Function to delete an existing element


void deleteElement(Node*& head, int data) {
if (!head) {
cout << "List is empty.\n";
return;
}

if (head->data == data) { // Delete the first node


Node* temp = head;
head = head->next;
delete temp;
cout << "Element deleted successfully.\n";
return;
}

Node* current = head;


while (current->next && current->next->data != data) {
current = current->next;
}

if (!current->next) {
cout << "Element not found.\n";
return;
}

Node* temp = current->next;


current->next = temp->next;
delete temp;
cout << "Element deleted successfully.\n";
}

// Function to search an element


void searchElement(Node* head, int data) {
Node* current = head;
while (current) {
if (current->data == data) {
cout << "Element found: " << data << "\n";
return;
}
current = current->next;
}
cout << "Element not found.\n";
}

// Function to display all elements


void displayElements(Node* head) {
if (!head) {
cout << "List is empty.\n";
return;
}

Node* current = head;


while (current) {
cout << current->data << " -> ";
current = current->next;
}
cout << "NULL\n";
}

// Main function with menu-driven interface


int main() {
Node* head = nullptr;
int choice, value;

do {
cout << "\nMenu:\n";
cout << "1. Insert an element\n";
cout << "2. Delete an element\n";
cout << "3. Search for an element\n";
cout << "4. Display all elements\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter value to insert: ";
cin >> value;
insertElement(head, value);
break;

case 2:
cout << "Enter value to delete: ";
cin >> value;
deleteElement(head, value);
break;

case 3:
cout << "Enter value to search: ";
cin >> value;
searchElement(head, value);
break;

case 4:
displayElements(head);
break;

case 5:
cout << "Exiting program.\n";
break;

default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 5);

return 0;
}

Explanation:

 createNode(): Creates a new node with the given data.


 insertElement(): Inserts a new element in the correct position to keep the list in
ascending order.
 deleteElement(): Deletes an element if it exists in the list.
 searchElement(): Searches for an element in the list.
 displayElements(): Displays all elements of the linked list.
 Menu-driven interface: The user can choose which operation to perform, and the program
loops until the user chooses to exit.

This program will maintain the linked list in ascending order and allow the user to perform
the required operations interactively.

You might also like