创建带头节点的循环单链表,无头节点的循环单链表,实现循环单链表逆置和左移

#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);
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值