链表的销毁

#include <stdio.h>
#include <stdlib.h>


typedef int ElemType;
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node
{
    ElemType data;
    Position  next;
};


List DisposeList(List L);


int main()
{
    List L=CreateList();
    /* 
    ´Ë´¦ÓɲâÊÔ´úÂë×Ô¶¯Ìí¼Ó£¬
    ²âÊÔList DisposeList(List L)º¯Êý£¬
    ÄãÖ»ÐèÍê³ÉList DisposeList(List L)º¯Êý¼´¿É
    */
    
    return 0;
}
List DisposeList(List L)
{

Node *p;    //构建新指针

p->next=NULL; p节点指向的下一个为空
free(p);把p释放
return NULL;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是C语言完成单链表的五个基本操作的代码和解释: 1. 创建链表 ```c #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; struct Node* createList(int n) { struct Node *head, *p, *q; int i; head = (struct Node*)malloc(sizeof(struct Node)); head->next = NULL; q = head; for (i = 0; i < n; i++) { p = (struct Node*)malloc(sizeof(struct Node)); scanf("%d", &p->data); p->next = NULL; q->next = p; q = p; } return head; } ``` 解释:首先定义了一个结构体Node,包含数据域data和指针域next。createList函数用于创建链表,参数n表示链表中节点的个数。首先创建头节点head,并将其next指针置为NULL。然后用q指针指向头节点,循环n次,每次创建一个新节点p,输入数据并将其next指针置为NULL,将q的next指针指向p,再将q指向p,最后返回头节点head。 2. 销毁链表 ```c void destroyList(struct Node* head) { struct Node* p = head; while (p != NULL) { head = head->next; free(p); p = head; } } ``` 解释:destroyList函数用于销毁链表,参数head为头节点。首先定义一个指针p指向头节点,循环遍历链表,每次将head指向下一个节点,释放p所指向的节点,再将p指向head,直到p指向NULL。 3. 在链表的最前面插入元素 ```c struct Node* insertAtBeginning(struct Node* head, int data) { struct Node* p = (struct Node*)malloc(sizeof(struct Node)); p->data = data; p->next = head; head = p; return head; } ``` 解释:insertAtBeginning函数用于在链表的最前面插入元素,参数head为头节点,data为要插入的数据。首先创建一个新节点p,将其data域赋值为data,将其next指针指向head,再将head指向p,最后返回头节点head。 4. 在链表的最后面插入元素 ```c struct Node* insertAtEnd(struct Node* head, int data) { struct Node* p = (struct Node*)malloc(sizeof(struct Node)); p->data = data; p->next = NULL; if (head == NULL) { head = p; } else { struct Node* q = head; while (q->next != NULL) { q = q->next; } q->next = p; } return head; } ``` 解释:insertAtEnd函数用于在链表的最后面插入元素,参数head为头节点,data为要插入的数据。首先创建一个新节点p,将其data域赋值为data,将其next指针置为NULL。如果head为NULL,即链表为空,将head指向p;否则,定义一个指针q指向head,循环遍历链表,直到q的next指针为NULL,将q的next指针指向p,最后返回头节点head。 5. 判断链表是否为空 ```c int isEmpty(struct Node* head) { return head == NULL; } ``` 解释:isEmpty函数用于判断链表是否为空,参数head为头节点。如果head为NULL,即链表为空,返回1;否则,返回0。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值