数据结构,链表的销毁,报错。
一直报错,不知道销毁哪里有问题,希望解惑。
#include "stdio.h"
#include "malloc.h"
typedef int ElemType;
typedef struct node{
ElemType data;
struct node *next;
}LNode,*LinkList;
LinkList SListTail(int n)
{
LNode *news,*tail,*head,*s;
tail=(LNode *)malloc(sizeof(LNode));
s=tail;
ElemType i;
for(i=1;i<=n;i++)
{
news=(LNode *)malloc(sizeof(LNode));
news->data=i;
tail->next=news;
tail=news;
if(i==1)head=news;
}
free(s);
tail->next=head;
return head;
}
int DistoryList(LinkList L)//销毁链表
{
LNode *s;
while(L)
{
s=L;
L=L->next;
free(s);
}
return 1;
}
void main()//测试函数
{
LNode *head;
head=SListTail(10);
DistoryList(head);
printf("OK ");
}
你的错很明显啊
你的是循环链表,它的每个节点都不等于NULL的
你用
while(L) 循环来销毁它,当然要出错的
它要这样销毁
int DistoryList(LinkList L)//销毁链表
{
LNode *p,*q;
p=L->next;
while(p!=L) /* 没到表尾 */
{
printf("%p
",p);
q=p->next;
free(p);
p=q;
}
free(L);
return 1;
}
你起码要说一下报什么错吧
尝试一下冗余算法
链表是一个很基本的数据结构,其他的数据结构(如:栈、队列、二叉树等)都可以用链表来实现。销毁:是先销毁了链表的头,然后接着一个一个的把后面的销毁了,这样这个链表就不能再使用了,即把包括头的所有节点全部释放。清空:是先保留了链表的头,然后把头后面的所有的都销毁,最后把头里指向下一个的指针设为空,这样就相当与清空了,但这个链表还在,还可以继续使用;即保留了头,后面的全部释放。
清空是链表的头还在,可以继续插入节点;销毁就是链表没了,整个链表(包括头)的空间都被释放了,不能进行任何操作了。---链表有很多种,以下均指的是不带头结点的单向链表。清空链表与销毁链表的代码如下:[cpp] view plaincopy#include "stdlib.h" #include "stdio.h" { int num; //学号 float score; //分数,其他信息可以继续在下面增加字段 struct student *next; //指向下一节点的指针 }; 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; } 2、链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g
思路:常见的三指针方法
[cpp] view plaincopytypedef 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;
上一篇:设计需求分析对话