Chinaunix首页 | 论坛 | 博客
  • 博客访问: 28762
  • 博文数量: 7
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 80
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-21 09:13
文章存档

2011年(1)

2008年(6)

我的朋友
最近访客

分类: C/C++

2008-09-24 11:31:29

基于VC6.0和gcc调试通过

该函数实现二进制数加1后并输出,每次输入0或1,输入其他数字结束输入。
#include
#include
//----------------------------------------------------------
typedef struct creat{
    int bin_num;//存储定义的二进制数的变量,其只存储 0 or 1
    struct creat *next;//指向下一个结构体节点的指针
}node, *linklist;
 
//创建链表函数,用于存储输入的二进制数
//----------------------------------------------------------
linklist creat_list()
{
    int bin_num;
    int flag = 1;
    node *head, *p, *q;
    p = head = (node *)malloc(sizeof(node));
    while (flag) {//利用尾差法创建链表
        printf("please input bin num: ");
        scanf("%d", &bin_num);
        if (bin_num == 1 || bin_num == 0) {
            q = (node *)malloc(sizeof(node));
            q -> bin_num = bin_num;
            p -> next = q;
            p = q;
        } else {
            flag = 0;
            p -> next = NULL;
        }
    }/*while*/
    head = head -> next;//这儿如果不这样,在下面的show_list()函数
                        //中输出的量表将是带头节点的,第一个元素将是头节点里面的垃圾值
                        //如果不要这一句,也可以在输出是作调整
    return head;
}/*creat_list*/
 
 
//执行将输入的二进制数加 1
//----------------------------------------------------------
linklist add_list(linklist bin)
{
    node *p, *q, *r, *s;
    q = p = bin;
    while ( p != NULL) {
        if (p -> bin_num == 0)//判断如果二进制数中有为 0 的元素,则将q指向它
        {
            q = p;
        }
        p = p -> next;
    }/*while*/
    if (q != bin) {
        q -> bin_num = 1;//让二进制数等于 1
    } else {
        r = q -> next;
        s = (node *)malloc(sizeof(node));
        s -> bin_num = 0;
        s -> next = r;
        q -> next = s;
        q = s;
    }
    q = q -> next;
    while (q != NULL) {//让最后一个 0 后面的数都等于 0
        q -> bin_num = 0;
        q = q -> next;
    
    }
    return bin;
}/*add_list*/
 
//打印二进制数
//----------------------------------------------------------
void show_list(linklist bin)
{
    while (bin != NULL) {
        printf("%d ", bin -> bin_num);
        bin = bin -> next;
    }
}/*show_list*/
 
//----------------------------------------------------------
int main()
{
    int status;
    char ch;
    node *p, *bin;
    do {
        p = creat_list();
        printf("the bin_num add 1 means: ");
        show_list(p);
        printf("+ 1 = ");
        bin = add_list(p);//执行二进制数加 1
        show_list(bin);
        printf("\n");
        printf("do you want to go on ? (press 'y' to go on or press any key to exit): ");
        ch = getchar();
        fflush(stdin);
        if (ch == 'y' )
          status = 1;
        else
          status = 0;
    } while (status == 1);
    return 0;
}/*main*/
阅读(1429) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~