ds1
ds1
AIM-Create doubly linked list with nodes having information about an employee and
perform Insertion at front of doubly linked list and perform deletion at end of that doubly
linked list.
Theory-
Code-
#include <iostream>
#include <cstring>
struct Employee {
int id;
char name[50];
float salary;
};
struct Node {
Employee emp;
Node* prev;
Node* next;
};
Node* createNode(int id, const char name[], float salary) {
Node* newNode = new Node;
newNode->emp.id = id;
strcpy(newNode->emp.name, name);
newNode->emp.salary = salary;
newNode->prev = nullptr;
newNode->next = nullptr;
return newNode;
}
void insertFront(Node** head, int id, const char name[], float salary) {
Node* newNode = createNode(id, name, salary);
if (*head == nullptr) {
*head = newNode;
} else {
newNode->next = *head;
(*head)->prev = newNode;
*head = newNode;
}
}
void deleteEnd(Node** head) {
if (*head == nullptr) {
cout << "List is empty." << endl;
return;
}
Node* temp = *head;
while (temp->next != nullptr) {
temp = temp->next;
}
if (temp->prev == nullptr) {
*head = nullptr;
} else {
temp->prev->next = nullptr;
}
delete temp;
cout << "Node deleted from the end." << endl;
}
void displayList(Node* head) {
if (head == nullptr) {
cout << "List is empty." << endl;
return;
}
Node* temp = head;
while (temp != nullptr) {
cout << "ID: " << temp->emp.id << ", Name: " << temp->emp.name << ", Salary: " <<
temp->emp.salary << endl;
temp = temp->next;
}
}
int main() {
Node* head = nullptr;
cout << "Inserted at front" << endl;
insertFront(&head, 1, "Devansh", 220000);
insertFront(&head, 2, "Aditya", 55500);
insertFront(&head, 3, "Raj", 340000);
cout << "Doubly Linked List:" << endl;
displayList(head);
deleteEnd(&head);
cout << "\nDoubly Linked List after deleting from the end:" << endl;
displayList(head);
return 0;
}
OUTPUT-