51,715
社区成员




#include <stdio.h>
#include <malloc.h>
typedef struct LNode
{
char date;//元素域
struct LNode *next;//指向下一个结点的指针(指针域)
}LinkLode;
//头插法
void CreateListF(LinkLode *&L, char a[], int n)
{
LinkLode *s;
L=(LinkLode *)malloc(sizeof(LinkLode));
L->next=NULL;
for(int i=0; i<n; i++)
{
s=(LinkLode *)malloc(sizeof(LinkLode));
s->date=a[i];
s->next=L->next;
L->next=s;
}
}
//尾插法
void CreateListR(LinkLode *&L, char a[], int n)
{
LinkLode *s,*r;
L=(LinkLode *)malloc(sizeof(LinkLode));
L->next=NULL;
for(int i=0; i<n; i++)
{
s=(LinkLode *)malloc(sizeof(LinkLode));
s->date=a[i];
r->next=s;
r=s;
}
r->next=NULL;//最后需要指向空节点
}
//初始化单链表
void InitList(LinkLode *&L)
{
L=(LinkLode *)malloc(sizeof(LinkLode));
L->next=NULL;
}
//摧毁单链表需要一个一个结点free
void DestoryList(LinkLode *&L)
{
LinkLode *pre=L, *p=pre->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=p->next;
}
free(pre);
}
bool ListEmpty(LinkLode *L)
{
return (L->next==NULL);
}
int ListLength(LinkLode *L)
{
int i=0;
LinkLode *p=L;
while(p->next!=NULL)
{
i++;
p=p->next;
}
return i;
}
//输出单链表
void DispList(LinkLode *L)
{
LinkLode *p=L->next;
while(p!=NULL)
{
printf("%c ",p->date);
p=p->next;
}
printf("\n");
}
//找到对应位置的元素
bool GetElem(LinkLode *L,int i, char &e)
{
int j=0;
LinkLode *p=L;
if(i<=0) return false;
while(j<i && p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL) return false;
else
{
e=p->date;
return true;
}
}
//定位对应元素的位置
int LocateElem(LinkLode *L, char e)
{
int i=1;
LinkLode *p=L->next;
while(p!=NULL && p->date!=e)
{
i++;
p=p->next;
}
if(p==NULL) return 0;
else return i;
}
//插入元素
bool ListInsert(LinkLode *&L, int i, char e)
{
int j=0;
LinkLode *p=L,*s;
if(i<=0) return false;
while(p!=NULL && j<i-1)
{
j++;
p=p->next;
}
if(p==NULL) return false;
else
{
s=(LinkLode*)malloc(sizeof(LinkLode));
s->date=e;
s->next=p->next;
p->next=s;
return true;
}
}
//删除元素
bool ListDelete(LinkLode *&L,int i,char e)
{
int j=0;
LinkLode *p=L,*q;
if(i<=0) return false;
while(p!=NULL && j<i-1)
{
j++;
p=p->next;
}
if(p==NULL) return false;
else
{
q=(LinkLode *)malloc(sizeof(LinkLode));
q=p->next;
if(q==NULL) return false;
e=q->date;
p->next=q->next;
free(q);
return true;
}
}
int main()
{
LinkLode *h;
char e;
printf("单链表的基本运算如下:\n");
printf(" (1)初始化单链表h\n");
InitList(h);
printf(" (2)依次采用尾插法插入a,b,c,d,e元素\n");
ListInsert(h,1,'a');
ListInsert(h,2,'b');
ListInsert(h,3,'c');
ListInsert(h,4,'d');
ListInsert(h,5,'e');
printf(" (3)输出单链表h:"); DispList(h);
printf(" (4)单链表h的长度:%d\n",ListLength(h));
printf(" (5)单链表h为%s\n",(ListEmpty(h) ? "空" : "非空"));
GetElem(h,3,e);
printf(" (6)单链表h的第3个元素:%c\n",e);
printf(" (7)元素a的位置:%d\n",LocateElem(h,'a'));
printf(" (8)在第4个元素位置上插入f元素\n");
ListInsert(h,4,'f');
printf(" (9)输出单链表h:"); DispList(h);
printf(" (10)删除h的第3个元素\n");
ListDelete(h,3,e);
printf(" (11)输出单链表h:"); DispList(h);
printf(" (12)释放单链表h\n");
DestoryList(h);
return 0;
}