问题及代码:
/*2015,烟台大学计算机与控制工程学院
*作者:张瑞蕾
*完成日期:2015年9月21日
*版本:v1.0
*问题描述:定义单链表存储结构,用头插法和尾插法建立单链表。
*/
#include <stdio.h>
#include <malloc.h>
typedef int ElemType;
typedef struct LNode //定义单链表结点类型
{
ElemType data;
struct LNode *next; //指向后继结点
} LinkList;
void CreateListF(LinkList *&L,ElemType a[],int n);//头插法建立单链表
void CreateListR(LinkList *&L,ElemType a[],int n);//尾插法建立单链表
void DestroyList(LinkList *&L); //销毁单链表
void DispList(LinkList *L); //输出单链表
int main()
{
LinkList *L1, *L2;
ElemType a[8]= {7, 9, 8, 2, 0, 4, 6, 3};
CreateListF(L1, a, 8);
printf("头插法建表结果:");
DispList(L1);
CreateListR(L2, a, 6);
printf("尾插法建表结果:");
DispList(L2);
DestroyList(L1);
DestroyList(L2);
return 0;
}
void CreateListF(LinkList *&L,ElemType a[],int n)
{
LinkList *s;
int i;
L=(LinkList *)malloc(sizeof(LinkList));
L->next=NULL;
for(i=0;i<n;i++)
{
s=(LinkList *)malloc(sizeof(LinkList));
s->data=a[i];
s->next=L->next;
L->next=s;
}
}
void CreateListR(LinkList *&L,ElemType a[],int n)
{
LinkList *s,*r;
int i;
L=(LinkList *)malloc(sizeof(LinkList));
r=L;
for(i=0;i<n;i++)
{
s=(LinkList *)malloc(sizeof(LinkList));
s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
void DestroyList(LinkList *&L)
{
LinkList *pre=L,*p=L->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=pre->next;
}
free(pre);
}
void DispList(LinkList *L)
{
LinkList *p=L->next;
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
printf("\n");
}
运行结果:
学习心得:
学习了头插法和尾插法两种方法建立单链表,两种方法既有其相通,也有其差别。