#1209二进制链表转整数

正常(暴力)思路:

  链表逆置再一个一个拿,如下:

    

 if(head == NULL) {
         return head;
     }
    struct ListNode*p=head;
    struct ListNode*z;
    z=(struct ListNode*)malloc(sizeof(struct ListNode));
    z->next=NULL;
    int i=1;
    while(p){
        struct ListNode*node;
        node=(struct ListNode*)malloc(sizeof(struct ListNode));
        node->val=p->val;
        node->next=z->next;
        z->next=node;
        p=p->next;
    }
    int result=0;
    struct ListNode*q=z->next;
    while(q){
        result=result+q->val*i;
        i=i*2;
        q=q->next;
    }
    return result;
简单思路:如力扣
 struct ListNode*p=head;
     int i=0;
     while(p!=NULL){
         i=i*2+p->val;
         p=p->next;
      }
     return i
posted on 2021-05-27 23:32  IN_A_Daze  阅读(66)  评论(0)    收藏  举报