ที่นี่ เราจะสร้างฟังก์ชันที่จะลบองค์ประกอบทั้งหมดของ linked list ทีละตัว
ใน C/C++ ไม่มีฟังก์ชันเฉพาะสำหรับทำงานนี้ แต่ใน Java มี automatic garbage collection ช่วยให้ลบ linked list ได้ง่ายขึ้น
ตอนนี้ มาดูการนำโปรแกรมนี้ไปใช้:
ตัวอย่าง
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
void deleteLinkedList(Node** head_ref) {
Node* current = *head_ref;
Node* next;
while (current != NULL) {
cout << current->data << "\t";
next = current->next;
free(current);
current = next;
}
*head_ref = NULL;
}
void push(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main() {
Node* head = NULL;
push(&head, 25);
push(&head, 10);
push(&head, 5);
push(&head, 90);
push(&head, 68);
cout << "Elements of linked list: ";
deleteLinkedList(&head);
cout << "\nLinked list deleted";
return 0;
}
ผลลัพธ์
Elements of linked list: 68 90 5 10 25 Linked list deleted