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 <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
#define MASIZE 100
typedef struct LNode
{
char data;
struct LNode *next;
}LNode,*LinkList;
void ListCreat(LinkList &L)//初始化單鏈表
{
L=(LNode*)malloc(sizeof(LNode));
L->next=NULL;
cout<<0<<endl;
}
void ListInsert(LinkList &L,int n)//插入數據
{
LNode *cur,*rear;
rear=L;
for(int i=0;i<n;i++)
{
cur=(LNode*)malloc(sizeof(LNode));
scanf("%c",&cur->data);
cur->next=NULL;
rear->next=cur;
rear=cur;
}
}
void Linsert(LinkList L,char a,int i)
{
LNode *p;
p=L;
i--;
while(i--)
{
p=p->next;
}
LNode *q;
q=(LNode*)malloc(sizeof(LNode));
q->data=a;
q->next=p->next;
p->next=q;
}
void Delete(LinkList &L,int i)//刪除某個鏈表元素
{
LNode *p=L,*q;
i--;
while(i--)
{
p=p->next;
}
q=(LNode*)malloc(sizeof(LNode));
q=p->next->next;
p->next=q;
}
int LengthList(LinkList &L)//求鏈表的長度
{
LNode *p;
int length=0;
p=L->next;
while(p)
{
length++;
p=p->next;
}
cout<<length<<endl;
}
void IsEmptyList(LinkList L)//判斷鏈表是否爲空
{
if(L->next)
cout<<"no"<<endl;
else
cout<<"yes"<<endl;
}
void PrintList(LinkList L)//輸出鏈表元素
{
LNode *p;
p=L->next;
cout<<p->data;
p=p->next;
while(p)
{
cout<<" "<<p->data;
p=p->next;
}
cout<<endl;
}
void Print(LinkList L,int i)
{
LNode *p;
p=L;
while(i--)
{
p=p->next;
}
cout<<p->data<<endl;
}
void LPrint(LinkList L,char a)//輸出某元素的位置
{
LNode *p;
p=L->next;
int length=0;
while(p)
{
length++;
if(p->data==a)
{
cout<<length<<endl;
break;
}
p=p->next;
}
}
int main()
{
int n;
LinkList L;
cin>>n;
ListCreat(L);
ListInsert(L,n);
PrintList(L);
LengthList(L);
IsEmptyList(L);
Print(L,3);
LPrint(L,'a');
Linsert(L,'x',4);
PrintList(L);
Delete(L,3);
PrintList(L);
free(L);
return 0;
}