Singly Linked List
Linked list बनाएँ, traverse और destroy करें।
Singly Linked List क्या है?
हर node value और अगले node का link रखता है।
महत्वपूर्ण बातें
- Operations से पहले invariants तय करें।
- Empty, full और allocation-failure cases संभालें।
- Complexity और ownership साथ मापें।
देखें यह कैसे काम करता है
शुरुआत या आख़िर में नोड जोड़ें और किसी नोड पर क्लिक करके उसे हटाएँ। head से NULL तक next पॉइंटर का पीछा करने के लिए चलाएँ दबाएँ।
C और C++ code examples
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
int main(void) {
Node *head = NULL;
for (int value = 3; value >= 1; --value) {
Node *node = malloc(sizeof *node);
if (!node) return 1;
*node = (Node){value, head};
head = node;
}
while (head) {
Node *next = head->next;
printf("%d ", head->value);
free(head);
head = next;
}
puts("");
return 0;
}
1 2 3
#include <iostream>
#include <memory>
struct Node {
int value;
std::unique_ptr<Node> next;
};
int main() {
std::unique_ptr<Node> head;
for (int value = 3; value >= 1; --value) {
head = std::make_unique<Node>(Node{value, std::move(head)});
}
for (Node *node = head.get(); node; node = node->next.get()) {
std::cout << node->value << ' ';
}
std::cout << '\n';
}
1 2 3
C और C++ की तुलना
C malloc से nodes बनाकर हर node free करता है; C++ unique_ptr head destroy होने पर chain स्वतः release करता है।
Structures और operations अलग, allocation स्पष्ट होता है।
Classes और containers invariants और resources manage करते हैं।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- Empty और capacity boundary tests जोड़ें।
- Cleanup लागू कर leaks जाँचें।
- Standard container से तुलना करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज