• 【C语言】用单链表实现一个二进制数加1的运算。


    #include
    #include
    #include
    #include
    #include

    struct node
    {
        int data;
        struct node *next;
    };
    int main()
    {
        int count=0;
        char a[80];
        scanf("%s",a);
        struct node *p,*q,*h;
        h= (struct node *)malloc(sizeof(struct node));
        p= (struct node *)malloc(sizeof(struct node));
        q= (struct node *)malloc(sizeof(struct node));
        h->next = p;
        for(int i=strlen(a)-1;i>0;i--)//倒序读取二进制数并存入单链表
        {
            p->data = a[i] - '0';//将char类型转化为int
            p->next = q;
            p = p->next;
            q = (struct node *)malloc(sizeof(struct node));


        }
        p->data = a[0] - '0';//最后一个结点的特殊处理
        p->next = NULL;

        p = h->next;
        int j=0;
        while(j     {
            if(p->data == 0)
            {
                p->data = 1;
                break;
            }
            else {
                    if(p->next == NULL)
                    {
                        q = (struct node *)malloc(sizeof(struct node));
                        q->data = 1;
                        q->next = NULL;
                        p->next = q;
                        p->data = 0;
                        break;
                    }
                    else {
                            p->data = 0;
                            p=p->next;


                        }
            }
        }
        p = h->next;
        for(;p->next!=NULL;count++)//count计算单链表的长度
        {
            p = p->next;
        }
        p = h->next;
        for(int m=0;m<=count;m++)//倒序输出单链表的数据
        {
            for(int n=m;n         {
                p = p->next;
            }
            printf("%d",p->data);
            free(p);
            p = h->next;
        }
        return 0;

    }

  • 相关阅读:
    小米汽车超级工厂智能物流
    容器化 Spring Boot 代码的 9 个技巧
    申请测试号进行练习
    postman使用方法
    Nginx配置负载均衡时访问地址无法生效
    软设上午题错题知识点7
    Redis:高效的数据存储与缓存解决方
    mysql建数据库时我们的字符集如何选择
    C语言函数章--该如何学习函数?阿斗看了都说会学习了
    【Python学习笔记】Python近期总结
  • 原文地址:https://blog.csdn.net/Klay_thompson11/article/details/126600548