链表的移动

前言

个人小记


一、代码如下

#include<stdio.h>
#include <stdlib.h>
#define MAX_LEN 10
#include <time.h>
typedef struct Node
{
    int data;
    struct Node* next;
}Node;

Node* init_node(int val)
{
    Node* node=(Node*)malloc(sizeof(Node));
    node->data=val;
    node->next=NULL;
    return node;
}

Node* insert(Node* head,int pos,int val)
{
    Node New_head;
    New_head.next=head;
    Node* p=&New_head;
    for(int i=0;i<pos;i++)p=p->next;
    Node* node=init_node(val);
    node->next=p->next;
    p->next=node;
    return New_head.next;
}


void clear(Node* head)
{
    if(head==NULL)return ;
    for(Node* p=head,*q;p;p=q)
    {
        q=p->next;
        free(p);
    }
    head=NULL;
    return ;
}

void print(Node* head)
{
    Node* p=head;
    while(p)
    {
        printf("%3d",p->data);
        printf("->");
        p=p->next;
    }
    printf("\n");
}

int len_linklist(Node* head)
{
    int n=1;
    Node* p=head;
    while(p->next)
    {
        n++;
        p=p->next;
    }
    return n;
}

    
Node* moving_linklist(Node* head,int n)
{
    int len=len_linklist(head);
    n=n%len;
    Node* p=head,*q=head;
    for(int i=0;i<n;i++)q=q->next;
    while(q->next!=NULL)
    {
        p=p->next;
        q=q->next;
    }
    q->next=head;
    head=p->next;
    p->next=NULL;
    return head;
}

int main()
{
    srand((unsigned)time(0));
    Node* head=NULL;
    for(int i=0;i<MAX_LEN;i++)
    {
        head=insert(head,i,rand()%100);
    }
    print(head);
    int n;
    printf("请输入移动的个数:");
    scanf("%d",&n);
    head=moving_linklist(head,n);
    print(head);

    clear(head);
    return 0;
}

二、结果如下

 22-> 63-> 47-> 43-> 83-> 24-> 83-> 21-> 75-> 23->
请输入移动的个数:19
 63-> 47-> 43-> 83-> 24-> 83-> 21-> 75-> 23-> 22->
sjq@SEER:~/coding$ ./a.out 
 74-> 60->  1-> 23-> 82-> 83-> 19->  7-> 13->  1->
请输入移动的个数:10
 74-> 60->  1-> 23-> 82-> 83-> 19->  7-> 13->  1->
sjq@SEER:~/coding$ ./a.out 
 60-> 21->  8-> 57-> 71->  0-> 26->  7-> 77-> 34->
请输入移动的个数:8 
  8-> 57-> 71->  0-> 26->  7-> 77-> 34-> 60-> 21->
sjq@SEER:~/coding$ ./a.out 
 24-> 34-> 36-> 14-> 66-> 16-> 39-> 50-> 37-> 15->
请输入移动的个数:0
 24-> 34-> 36-> 14-> 66-> 16-> 39-> 50-> 37-> 15->
  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值