动态内存分配以及链表的基本操作

xiaoxiao2021-02-28  105

一、c/c++中的动态内存分配

1、在c中申请动态内存使用的是malloc函数,malloc函数位于stdlib.h头文件下,其返回类型是申请的同变量类型的指针。例如申请一个node类型结构体变量使用以下的方式: node* p = (node*) malloc(sizeof(node)); 用malloc函数申请的内存空间用完后需要使用free函数释放,例如释放前面申请的内存空间 :free(p); 2、在c++中申请动态内存使用的是new运算符,其返回类型为申请的同变量类型的指针,例如申请一个node类型的结构体变量使用以下的方式: node* p = new node; 用new申请的内存空间用完后需要使用delete运算符释放,例如释放前面申请的内存空间:delete(p);

二、链表的基本操作

1、创建链表 以创建结点类型为int型的链表为例,比如创建一个链表:1 -> 2 -> 3 -> 4 -> 5 struct node{ int data; node* next; }; node* create(int Array[]){ node *p, *pre, *head; head = new node; head->next = NULL; pre = head; for(int i = 0; i < 5; i++){ p = new node; p->data = Array[i]; p->next = NULL; pre->next = p; pre = p; } return head; } 2、查找元素 int search(node* head, int x){ int count = 0; node* p = head->next; while(p != NULL){ if(p->data == x){ count++; } p = p->next; } return count; } 3、插入元素 void insert(node* head, int pos, int x){ node* p = head; for(int i = 0; i < pos - 1; i++){ p = p->next; } node* q = new node; q->data = x; q->next = p->next; p->next = q; } 4、删除元素 void del(node* head, int x){ node* p = head->next; node* pre = head; while(p != NULL){ if(p->data = x){ pre->next = p->next; delete(p); p = pre->next; } else{ pre = p; p = p->next; } } }
转载请注明原文地址: https://www.6miu.com/read-59730.html

最新回复(0)