7-1 jmu-ds-循环单链表的基本运算(数据结构之循环链表)
实现循环单链表的基本运算:初始化、插入、删除、求表的长度、判空、释放。
(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 <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstring>
using namespace std;
typedef struct LNode
{
char data;
struct LNode *next;
}LNode,*LinkList;
void init(LinkList &L)
{
L=(LNode*)malloc(sizeof(LNode));
L->next=L;
cout<<1<<endl;
}
void push(LinkList &L)
{
int n;
cin>>n;
if(n==0) return ;
LNode *p;
p=(LNode*)malloc(sizeof(LNode));
cin>>p->data;
p->next=L; L->next=p; n--;
while(n--)
{
LNode *p1;
p1=(LNode*)malloc(sizeof(LNode));
cin>>p1->data;
p1->next=L;
p->next=p1;
p=p1;
}
}
void print(LinkList L)
{
LNode *p=L->next;
if(p==L)
{
return ;
}
while(p!=L)
{
if(p->next!=L)
cout<<p->data<<" ";
else cout<<p->data<<endl;
p=p->next;
}
}
void length(LinkList L)
{
LNode *p=L->next;
int res=0;
while(p!=L)
{
p=p->next;
res++;
}
cout<<res<<endl;
}
void empty_(LinkList L)
{
if(L->next==L) cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
void three(LinkList L,int n)
{
LNode *p=L;
while(n--)
{
p=p->next;
}
cout<<p->data<<endl;
}
void zifu(LinkList L,char c)
{
LNode *p=L->next;
int res=1;
while(1)
{
if(p->data==c)
{
cout<<res<<endl; return ;
}
p=p->next; res++;
}
}
void push_(LinkList &L,char c,int n)
{
LNode *p=L;
n--;
while(n--)
{
p=p->next;
}
LNode *p1;
p1=(LNode*)malloc(sizeof(LNode));
p1->data=c;
p1->next=p->next;
p->next=p1;
}
void delete_(LinkList &L,int n)
{
LNode *p=L;
n--;
while(n--)
{
p=p->next;
}
p->next=p->next->next;
}
int main()
{
LinkList L;
init(L);
push(L);
print(L);
length(L);
empty_(L);
three(L,3);
zifu(L,'a');
push_(L,'w',4);
print(L);
delete_(L,5);
print(L);
free(L);
return 0;
}