用 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