7-3 jmu-ds-单链表的基本运算(15 分)
实现单链表的基本运算:初始化、插入、删除、求表的长度、判空、释放。
(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
#include<bits/stdc++.h>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef char ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
Status CreatList(LinkList &L)
{
LNode *cur;
cur=(LNode*)malloc(sizeof(LNode));
if(!cur) exit(OVERFLOW);
L=cur;
cur->next=NULL;
cout<<0<<endl;
return OK;
}
Status LinkListInsert(LinkList &L,int pos,ElemType &e)
{
if(pos<=0) return FALSE;
LNode *cur,*rea,*tmp;
rea=L;
cur=L->next;
int num=1;
while(num<pos&&cur){
cur=cur->next; num++; rea=rea->next;
}
if(num<pos) return FALSE;
tmp=(LNode*)malloc(sizeof(LNode));
if(!tmp) exit(OVERFLOW);
tmp->data=e;
tmp->next=NULL;
tmp->next=cur;
rea->next=tmp;
return OK;
}
Status GetVal_L(LinkList &L,int pos)
{
if(pos<=0) return FALSE;
LNode *cur;
cur=L->next;
int num=1;
while(cur&&num<pos){
num++; cur=cur->next;
}
if(num<pos) return FALSE;
cout<<cur->data<<endl;
}
Status Print_L(LinkList &L)
{
LNode *cur;
cur=L->next;
int k=0;
while(cur){
if(k==0) cout<<cur->data;
else cout<<" "<<cur->data;
cur=cur->next;
k++;
}
cout<<endl;
}
Status Locate_L(LinkList &L,ElemType e)
{
LNode *cur;
cur=L->next;
int num=1;
while(cur&&cur->data!=e){
cur=cur->next;
num++;
}
if(!cur) return FALSE;
cout<<num<<endl;
return OK;
}
Status JudgeEmpty_L(LinkList L)
{
/*L=L->next;
if(L) return OK;
else return FALSE;*/
return L->next ? FALSE : TRUE;
}
Status Length_L(LinkList L)
{
LNode *cur;
cur=L->next;
int length=0;
while(cur){
length++;
cur=cur->next;
}
cout<<length<<endl;
return OK;
}
Status ListDelete(LinkList &L,int pos)
{
if(pos<=0) return FALSE;
LNode *cur,*rea;
cur=L->next;
rea=L;
int num=1;
while(num<pos&&cur){
cur=cur->next;
rea=rea->next;
num++;
}
if(num<pos) return FALSE;
rea->next=cur->next;
return OK;
}
void ListFree_L(LinkList &L)
{
LNode *cur,*rea;
cur=L->next;
rea=L;
while(cur){
free(rea);
rea=cur;
cur=cur->next;
}
free(cur);
}
int main()
{
int n;
ElemType e;
LinkList L;
if(CreatList(L)==OK){
scanf("%d",&n);
for(int i=1;i<=n;i++){
cin>>e;
LinkListInsert(L,i,e);
}
Print_L(L);
Length_L(L);
if(JudgeEmpty_L(L)) cout<<"yes"<<endl;
else cout<<"no"<<endl;
GetVal_L(L,3);
e='a';
Locate_L(L,e);
e='x';
LinkListInsert(L,4,e);
Print_L(L);
ListDelete(L,3);
Print_L(L);
ListFree_L(L);
}
return 0;
}