链表的反转--pro

前言

个人小记


一、怎么pro了?

输入两个数值表示要翻转的位置

二、代码

#include<stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_LEN 10
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;
    Node* p=&New_head;
    New_head.next=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);
    }
    return ;
}

void print(Node* head)
{
    Node* p=head;
    while(p)
    {
        printf("%4d",p->data);
        printf("->");
        p=p->next;
    }
    printf("\n");
    return ;
}
Node* reverlinklist(Node* head,int left,int right)
{
    if(head==NULL)
    {
        printf("链表为空\n");
        return head;
    }
    if(left==0&&right==0)return head;
    if(left!=0)
    {
        head->next=reverlinklist(head->next,left-1,right-1);
    }
    else if(left==0&&right!=0)
    {
        Node* tail=head->next;
        Node* New_head=reverlinklist(tail,left,right-1);
        head->next=tail->next;
        tail->next=head;
        head=New_head;
    }
    return head;
}


int main()
{
    srand((unsigned)time(0));
    Node* head=NULL;
    for(int i=0;i<MAX_LEN;i++)
    {
        head=insert(head,i,(i+rand()%100));
    }
    printf("当前链表为:\n");
    print(head);
    int left,right;
    printf("请输入要反转链表的位置范围:\n");
    scanf("%d%d",&left,&right);
    if(left<=right&&right<MAX_LEN&&left>=0&&right>=0)
    {
        head=reverlinklist(head,left,right);
        printf("反转后的链表为:\n");
        print(head);
    }
    else printf("输入有误\n");  
    clear(head);
    return 0;
}

三、结果

当前链表为:
  31->  51->  85->  43->  29->  78->  69->  13->  17->  43->
请输入要反转链表的位置范围:
1 4
反转后的链表为:
  31->  29->  43->  85->  51->  78->  69->  13->  17->  43->
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值