여기에서는 연결 리스트의 모든 요소를 하나씩 삭제하는 함수를 만들 것입니다.
c/c++에서는 이 작업을 수행하는 특정 기능이 없지만 Java에서는 자동 가비지 컬렉션을 수행하여 연결 목록을 쉽게 삭제할 수 있습니다.
이제 이 프로그램의 구현을 살펴보겠습니다.
예시
#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";
} 출력
Elements of linked list : 68 90 5 10 25 Linked list deleted