1:单链表的基本运算
总时间限制: 5000ms 内存限制: 65535kB
描述
实现单链表的基本运算:初始化、插入、删除、求表的长度、判空、释放。
(1)初始化单链表L,输出L->next的值;
(2)依次采用尾插法插入元素:输入分两行数据,第一行是尾插法需要插入的字符数据的个数,第二行是具体插入的字符数据。
(3)输出单链表L;
(4)输出单链表L的长度;
(5)判断单链表L是否为空;
(6)输出单链表L的第3个元素;
(7)输出元素a的位置;
(8)在第4个元素位置上插入‘x’元素;
(9)输出单链表L;
(10)删除L的第3个元素;
(11)输出单链表L;
(12)释放单链表L。
输入
两行数据,第一行是尾插法需要插入的字符数据的个数,第二行是具体插入的字符数据。
输出
按照程序要求输出
样例输入
5
a b c d e
样例输出
0
a b c d e
5
no
c
1
a b c x d e
a b x d e
ac代码:
#include<iostream>
#include<cstdlib>
using namespace std;
const int MAXSIZE=100;
#define ElemType char
typedef struct LNode{
ElemType data;
struct LNode *next;
}LinkNode;
bool InitList(LinkNode *&L)
{
L=(LinkNode *)malloc(sizeof(LinkNode));
if(!L)
return false;
L->next=NULL;
}
void CreateListF(LinkNode *&L,ElemType a[],int n)//头插法
{
LinkNode *s;
int i;
L=(LinkNode *)malloc(sizeof(LinkNode));
L->next=NULL;
for(i=0;i<n;i++)
{
s=(LinkNode *)malloc(sizeof(LinkNode));
s->data=a[i];
s->next=L->next;
L->next=s;
}
}
void CreateListR(LinkNode *&L,ElemType a[],int n)//尾插法
{
LinkNode *s,*r;
int i;
L=(LinkNode *)malloc(sizeof(LinkNode));
r=L;
for(i=0;i<n;i++)
{
s=(LinkNode *)malloc(sizeof(LinkNode));
s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
void DispList(LinkNode *&L)
{
LinkNode *p=L->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int GetLength(LinkNode *L)
{
int i=0;
LinkNode *p=L->next;
while(p!=NULL)
{
i++;
p=p->next;
}
return i;
}
bool GetElem(LinkNode *&L,int i,ElemType &e)
{
int j=0;
LinkNode *p=L;
while(j<i&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else{
e=p->data;
return true;
}
}
int LocateElem(LinkNode *&L,ElemType e)
{
int i=1;
LinkNode *p=L->next;
while(p!=NULL&&p->data!=e)
{
p=p->next;
i++;
}
if(p==NULL)
return (0);
else
return (i);
}
bool ListEmpty(LinkNode *L)
{
return(L->next==NULL);
}
bool ListInsert(LinkNode *&L,int i,ElemType e)
{
int j=0;
LinkNode *p=L,*s;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else{
s=(LinkNode *)malloc(sizeof(LinkNode));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
}
bool ListDelete(LinkNode *&L,int i,ElemType &e)
{
int j=0;
LinkNode *p=L,*q;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
q=p->next;
if(q==NULL)
return false;
e=q->data;
p->next=q->next;
free(q);
return true;
}
}
void DestoryList(LinkNode *&L)
{
LinkNode *pre=L,*p=L->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=pre->next;
}
free(pre);
}
int main()
{
LinkNode *L;
ElemType e;
InitList(L);
cout<<L->next<<endl;
int n;
char a[MAXSIZE];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
CreateListR(L,a,n);
DispList(L);
cout<<GetLength(L)<<endl;
if(!ListEmpty(L))
{
cout<<"no"<<endl;
}
else
{
cout<<"yes"<<endl;
}
// ElemType e;
if(GetElem(L,3,e))
{
cout<<e<<endl;
}
cout<<LocateElem(L,'a')<<endl;
ListInsert(L,4,'x');
DispList(L);
ListDelete(L,3,e);
DispList(L);
DestoryList(L);
}