#include <stdio.h>
#include <stdlib.h>
typedef char Elem;
typedef struct Linknode
{
Elem data;
struct Linknode *next;
}Linknode ,*Linklist;
//创建链表
void createL(Linklist *L)
{
*L=(Linklist)malloc(sizeof(Linknode));
Linknode *pnode=(Linknode *)malloc(sizeof(Linknode));
Linknode *tail=(*L);
tail->next=*L;
Elem data;
scanf("%c",&data);
pnode->data=data;
pnode->next=tail->next;
tail->next=pnode;
tail=tail->next;
while(1)
{
scanf("%c",&data);
if(data=='#')
{
break ;
}
Linknode *temp=(Linknode *)malloc(sizeof(Linknode));
temp->data=data;
temp->next=tail->next;
tail->next=temp;
tail=tail->next;
}
}
//逆置链表
void reverse(Linklist L)
{
if(L==NULL)
return ;
Linknode *pnode=L->next;
L->next=L;
while(pnode!=L)
{
Linknode *temp=pnode;
//printf("%c\n",pnode->data);
pnode=pnode->next;
temp->next=L->next;
L->next=temp;
}
//printf("%c %c %c",L->next->data,L->next->next->data,L->next->next->next->data);
print(L);
}
//创建无头节点的循环单链表
void createNoheadL(Linklist *head)
{
*head=(Linklist)malloc(sizeof(Linknode));
Elem data;
scanf("%c",&data);
(*head)->data=data;
(*head)->next=(*head);
Linknode *tail=(*head);
while(1)
{
scanf("%c",&data);
if(data=='#')
break;
Linknode *pnode=(Linknode *)malloc(sizeof(Linknode));
pnode->data=data;
tail->next=pnode;
tail=tail->next;
}
tail->next=(*head);
}
//循环左移k个节点
void move(Linklist *head,int k)
{
if((*head)==NULL)
{
return ;
}
int cnt=1;
Linknode *pnode=(*head);
while(cnt<=k)
{
pnode=pnode->next;
cnt++;
}
(*head)=pnode;
}
//打印无头节点循环链表
printNohead(Linklist head)
{
if(head==NULL)
return;
Linknode *pnode =head;
do
{
printf("%c\n",pnode->data);
pnode=pnode->next;
}while(pnode!=head);
}
//打印链表
void print(Linklist L)
{
if(L==NULL)
return;
Linknode *pnode=L->next;
printf("%c",pnode->data);
while(pnode!=L)
{
printf("%c\n",pnode->data);
pnode=pnode->next;
}
}
int main()
{
Linklist *L;
createL(&L);
print(L);
reverse(L);
print(L);
Linklist *head;
createNoheadL(&head);
printNohead(head);
move(&head,5);
printNohead(head);
}
创建带头节点的循环单链表,无头节点的循环单链表,实现循环单链表逆置和左移
最新推荐文章于 2023-04-05 14:09:10 发布