用 C++ 程式設計編寫一個函式來刪除一個連結串列
在此,我們將建立一個函式來逐個刪除連結串列的所有元素。
在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP