0% found this document useful (0 votes)
6 views2 pages

linked_list_operations

This document contains a C++ implementation of a singly linked list with various operations such as inserting and deleting nodes at the start, end, and specific positions. It also includes a display function to print the list. The main function demonstrates the usage of these linked list operations.

Uploaded by

t61212708
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

linked_list_operations

This document contains a C++ implementation of a singly linked list with various operations such as inserting and deleting nodes at the start, end, and specific positions. It also includes a display function to print the list. The main function demonstrates the usage of these linked list operations.

Uploaded by

t61212708
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

struct Node {
int data;
Node* next;
Node(int val): data(val), next(nullptr) {}
};

class LinkedList {
private:
Node* head;
public:
LinkedList(): head(nullptr) {}

// Insert at the start


void insertAtStart(int val) {
Node* n = new Node(val);
n->next = head;
head = n;
}

// Insert at the end


void insertAtEnd(int val) {
Node* n = new Node(val);
if (!head) { head = n; return; }
Node* temp = head;
while (temp->next) temp = temp->next;
temp->next = n;
}

// Delete at the start


void deleteAtStart() {
if (!head) return;
Node* temp = head;
head = head->next;
delete temp;
}

// Delete at the end


void deleteAtEnd() {
if (!head) return;
if (!head->next) { delete head; head = nullptr; return; }
Node* temp = head;
while (temp->next->next) temp = temp->next;
delete temp->next;
temp->next = nullptr;
}

// Delete at a specific position (middle)


void deleteAtPosition(int pos) {
if (pos < 1 || !head) return;
if (pos == 1) { deleteAtStart(); return; }
Node* temp = head;
for (int i = 1; temp && i < pos - 1; ++i)
temp = temp->next;
if (!temp || !temp->next) return;
Node* toDelete = temp->next;
temp->next = toDelete->next;
delete toDelete;
}

// Display the list


void display() {
Node* temp = head;
while (temp) {
std::cout << temp->data << " -> ";
temp = temp->next;
}
std::cout << "NULL\n";
}
};

int main() {
LinkedList list;
list.insertAtEnd(10);
list.insertAtStart(5);
list.insertAtEnd(15);
list.display();

// Delete the second element


list.deleteAtPosition(2);
list.display();

// Delete at start and end


list.deleteAtStart();
list.display();
list.deleteAtEnd();
list.display();

return 0;
}

You might also like