实现循环单链表的基本运算:初始化、插入、删除、求表的长度、判空、释放。
(1)初始化循环单链表L,输出(L->next==L)的逻辑值;
(2)依次采用尾插法插入元素:输入分两行数据,第一行是尾插法需要插入的字符数据的个数,第二行是具体插入的字符数据。
(3)输出循环单链表L;
(4)输出循环单链表L的长度;
(5)判断循环单链表L是否为空;
(6)输出循环单链表L的第3个元素;
(7)输出元素a的位置;
(8)在第4个元素位置上插入‘w’元素;
(9)输出循环单链表L;
(10)删除L的第5个元素;
(11)输出循环单链表L;
(12)释放循环单链表L。
输入格式:
两行数据,第一行是尾插法需要插入的字符数据的个数,第二行是具体插入的字符数据。
输出格式:
按照程序要求输出
输入样例:
5
a b c d e
输出样例:
1
a b c d e
5
no
c
1
a b c w d e
a b c w e
个人估计后台数据有点问题。。最后一个样例显示格式错误,但是题目中未提示某些特殊情况的具体格式。
#include <bits/stdc++.h>
using namespace std;
typedef struct LNode
{
char data;
struct LNode *next;
} LNode,*LinkList;
int Create_Linklist(LinkList& p)
{
LinkList t,head;
int n;
cin>>n;
head=p;
for(int i=0;i<n;i++){
t=(LinkList)malloc(sizeof(LNode));
cin>>t->data;
head->next=t;
head=head->next;
}
head->next=p;
return n;
}
void Print_Linklist(LinkList p)
{
LinkList head=p->next;
while(head!=p){
if(head->next==p)cout<<head->data;
else cout<<head->data<<" ";
head=head->next;
}
}
int Get_Length(LinkList p){
int cnt=0;
LinkList head=p->next;
while(head!=p){
cnt++;
head=head->next;
}
return cnt;
}
char Get_Element(LinkList p){
int cnt=1;
char e;
int temp=3;
if(Get_Length(p)<temp)temp=Get_Length(p);
LinkList head=p->next;
while(true){
if(cnt==temp){
e=head->data;
return e;
}
cnt++;
head=head->next;
}
}
int Get_Count(LinkList p,char e){
int cnt=1;
LinkList head=p->next;
while(head!=p){
if(head->data==e){
return cnt;
}
cnt++;
head=head->next;
}
return 0;
}
void Insert_Linklist(LinkList& p,int pos,char e){
if(pos<=0||Get_Length(p)<pos-1)return;
int cnt=2;
LinkList head=p->next,t;
while(head!=p){
if(cnt==pos){
t=(LinkList)malloc(sizeof(LNode));
t->data=e;
t->next=head->next;
head->next=t;
}
cnt++;
head=head->next;
}
}
void Delete_Linklist(LinkList& p,int pos){
if(pos<=0||Get_Length(p)<pos)return;
int cnt=2;
LinkList head=p->next;
while(head!=p){
if(cnt==pos){
LinkList t=head->next;
head->next=t->next;
free(t);
break;
}
cnt++;
head=head->next;
}
}
void List_free(LinkList& p)
{
LinkList head,rear;
head=p->next;
while(head!=p){
rear=head;
head=head->next;
free(rear);
}
}
int main()
{
LinkList l;
l=(LinkList)malloc(sizeof(LNode));
l->next=l;
if(l->next==l)cout<<1<<endl;
else cout<<0<<endl;
int cnt=Create_Linklist(l);
Print_Linklist(l);
cout<<endl;
cout<<cnt<<endl;
if(l->next==l)cout<<"yes"<<endl;
else cout<<"no"<<endl;
char e;
e=Get_Element(l);
cout<<e<<endl;
cnt=Get_Count(l,'a');
cout<<cnt<<endl;
Insert_Linklist(l,4,'w');
Print_Linklist(l);
cout<<endl;
Delete_Linklist(l,5);
Print_Linklist(l);
List_free(l);
return 0;
}