链表是一个很基本的数据结构,其他的数据结构(如:栈、队列、二叉树等)都可以用链表来实现。
销毁:是先销毁了链表的头,然后接着一个一个的把后面的销毁了,这样这个链表就不能再使用了,即把包括头的所有节点全部释放。
清空:是先保留了链表的头,然后把头后面的所有的都销毁,最后把头里指向下一个的指针设为空,这样就相当与清空了,但这个链表还在,还可以继续使用;即保留了头,后面的全部释放。清空是链表的头还在,可以继续插入节点;销毁就是链表没了,整个链表(包括头)的空间都被释放了,不能进行任何操作了。
---链表有很多种,以下均指的是不带头结点的单向链表。
清空链表与销毁链表的代码如下:
- #include "stdlib.h"
- #include "stdio.h"
- struct student
- {
- int num; //学号
- float score; //分数,其他信息可以继续在下面增加字段
- struct student *next; //指向下一节点的指针
- };
- //销毁链表
- int DestroyList(struct student *head)
- {
- struct student *p;
- if(head==NULL)
- return 0;
- while(head)
- {
- p=head->next;
- free(head);
- head=p;
- }
- return 1;
- }
- //清空链表
- int ClearList(struct student *head)
- {
- struct student *p,*q;
- if(head==NULL)
- return 0;
- p=head->next;
- while(p!=NULL)
- {
- q=p->next;
- free(p);
- p=q;
- }
- head->next=NULL;
- return 1;
- }
思路:常见的三指针方法
- typedef struct LinkNode
- {
- int data;
- struct LinkNode* next;
- }LinkNode , *LinkList;
- LinkList inverseList(LinkList head)
- {
- if(head == NULL || head->next == NULL)
- return head;
- LinkList pre = NULL;
- LinkList curr = head;
- LinkList next = NULL;
- while(curr && curr->next)
- {
- if(pre)
- pre->next = curr->next;
- else
- head = curr->next;
- pre = curr;
- next = curr->next->next;
- curr->next->next = curr;
- curr->next = next;
- curr = next;