Linked List Sample Program
Linked List Sample Program
Sample Program 1
#include <iostream>
struct Node {
int data;
Node* next;
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
// Destructor
~LinkedList() {
destroy();
}
};
int main() {
LinkedList list;
// 1. Appending nodes
list.append(10);
list.append(20);
list.append(30);
// 3. Inserting nodes
list.insert(15, 1); // Insert 15 at position 1
list.insert(5, 0); // Insert 5 at position 0 (head)
list.traverse();
// 4. Deleting nodes
list.remove(20); // Delete node with value 20
list.traverse();
list.remove(100); // Try to delete a non-existent value
return 0;
}
Sample Program 2
#include <iostream>
using namespace std;
public:
// Constructor
LinkedList() : head(nullptr) {}
// Destructor
~LinkedList() {
// Free all nodes
ListNode* current = head;
while (current != nullptr) {
ListNode* temp = current;
current = current->next;
delete temp;
}
}
int main() {
// Create a LinkedList for integers
LinkedList<int> intList;
return 0;
}