Linked List Implementation in C++ and Java
A linked list is a fundamental data structure that stores elements in nodes, where each node contains data and a reference (or pointer) to the next node. Unlike arrays, linked lists provide dynamic memory allocation and efficient insertion/deletion operations.
🌍 Why Linked Lists?
- Dynamic size: Unlike arrays, linked lists can grow or shrink at runtime.
- Efficient insertions/deletions: Adding or removing nodes doesn’t require shifting elements.
- Flexibility: Useful for implementing stacks, queues, and other abstract data types.
🛠️ Linked List in C++
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val) {
data = val;
next = nullptr;
}
};
class LinkedList {
Node* head;
public:
LinkedList() { head = nullptr; }
void insert(int val) {
Node* newNode = new Node(val);
if (!head) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next) temp = temp->next;
temp->next = newNode;
}
void display() {
Node* temp = head;
while (temp) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL\n";
}
};
int main() {
LinkedList list;
list.insert(10);
list.insert(20);
list.insert(30);
list.display(); // Output: 10 -> 20 -> 30 -> NULL
return 0;
}
🐍 Linked List in Java
class Node {
int data;
Node next;
Node(int val) {
data = val;
next = null;
}
}
class LinkedList {
Node head;
public void insert(int val) {
Node newNode = new Node(val);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) temp = temp.next;
temp.next = newNode;
}
public void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("NULL");
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(10);
list.insert(20);
list.insert(30);
list.display(); // Output: 10 -> 20 -> 30 -> NULL
}
}
📊 Comparison of C++ and Java Implementations
| Feature | C++ | Java |
|---|---|---|
| Memory Management | Manual (new/delete) | Automatic (Garbage Collection) |
| Syntax | Explicit pointers (Node*) | References (Node) |
| Flexibility | Closer to hardware | Safer, less error-prone |
| Output | cout | System.out.print |
📖 Conclusion
Linked lists in both C++ and Java demonstrate how nodes can be dynamically managed to store sequences of data. While C++ provides low-level control with pointers, Java simplifies memory management with garbage collection. Mastering linked lists is essential for understanding dynamic data structures and building more complex abstractions like stacks, queues, and graphs.
No comments:
Post a Comment