问题及代码
编写一个程序exp2-2.cpp,实现单链表的各种基本运算(假设单链表的元素类型为char),并在此基础上完成如下功能:
(1)初始化单链表h;
(2)采用尾插法依次插入元素a,b,c,d,e;
(3)输出单链表h;
(4)输出单链表h长度;
(5)判断单链表h是否为空;
(6)输出单链表h的第3个元素;
(7)输出元素a的位置;
(8)在第4个元素位置上插入元素f;
(9)输出单链表h;
(10)删除h的第3个元素;
(11)输出单链表h;
(12)释放单链表h。
代码#include <iostream>
#include<stdio.h>
#include<malloc.h>
#define SizeMax 50
using namespace std;
typedef char ElemType;
typedef struct Node
{
ElemType data;
struct Node *next;
} SqList;
void InitList(SqList *&h)
{
printf("(1)初始化单链表h\n");
h=(SqList *)malloc(sizeof(SqList));
h->next=NULL;
}
void Insert(SqList *&h,char x)
{
SqList *s,*p;
p=h;
while(p->next!=NULL)
p=p->next;
s=p;
p=(SqList *)malloc(sizeof(SqList));
p->data=x;
s->next=p;
p->next=NULL;
}
void Print(SqList *&h)
{
SqList *p=h->next;
while(p!=NULL)
{
printf("%c ",p->data);
p=p->next;
}
printf("\n");
}
void PrintLength(SqList *&h)
{
int n=0;
SqList *p=h;
while(p->next!=NULL)
{
n++;
p=p->next;
}
printf("%d\n",n);
}
bool SqNull(SqList *&h)
{
if(h->next==NULL)
return false;
else return true;
}
bool PrintData(SqList *&h,int i)
{
int j=0;
SqList *p=h;
while(j<i&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
printf("%c\n",p->data);
return true;
}
}
bool Find(SqList *&h,char x)
{
int i=1;
SqList *p=h->next;
while(p!=NULL&&p->data!=x)
{
p=p->next;
i++;
}
if(p==NULL)
return 0;
else
return i;
}
bool Insertinto(SqList *&h,int i,ElemType f)
{
int j=0;
SqList *s,*p=h;
i--;
while(j<i&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
s=(SqList *)malloc(sizeof(SqList));
s->data=f;
s->next=p->next;
p->next=s;
return true;
}
}
bool Delete(SqList *&h,int i)
{
int j=0;
SqList *q,*p=h;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
q=p->next;
if(q==NULL)
return false;
p->next=q->next;
free(q);
return true;
}
}
int main()
{
SqList *h;
InitList(h); //初始化单链表
ElemType a,b,c,d,e;
printf("(2)依次采用尾插法插入a,b,c,d,e元素:");
scanf("%c %c %c %c %c%*c",&a,&b,&c,&d,&e);
Insert(h,a);
Insert(h,b);
Insert(h,c);
Insert(h,d);
Insert(h,e);
printf("(3)输出单链表h:") ;
Print(h);
printf("(4)单链表h长度:") ;
PrintLength(h);
if(SqNull(h))
printf("(5)单链表h为非空\n");
else printf("(5)单链表h为空\n");
printf("(6)单链表h的第三个元素=");
PrintData(h,3);
printf("(7)元素a的位置:%d\n",Find(h,a));
ElemType f;
printf("(8)在第4个元素位置上插入f元素:");
scanf("%c",&f);
Insertinto(h,4,f);
printf("(9)输出单链表h:") ;
Print(h);
printf("(10)删除h的第三个元素\n") ;
Delete(h,3);
printf("(11)输出单链表h:") ;
Print(h);
printf("(12)释放单链表h:") ;
free(h);
return 0;
}
运算结果