编程语言
首页 > 编程语言> > 算法题---链表求和

算法题---链表求和

作者:互联网

 

 

 

// 链表求和
ListNode *addTwoList(ListNode *p, ListNode *q){
    ListNode *pCur = p;
    ListNode *qCur = q;
    ListNode *head = new ListNode(-1);
    ListNode *ret = head;
    int t = 0;
    int sum = 0;
    while( pCur !=NULL || qCur !=NULL || t!=0){
        sum = 0;
        if(pCur){
            sum += pCur->val;
            pCur = pCur->next;
        }
        if(qCur){
            sum += qCur->val;
            qCur = qCur->next;
        }
        sum += t;
        ret->next = new ListNode(sum % 10);
        ret = ret->next;
        t = sum / 10;
    }
    return head->next;
}

 

标签:---,ListNode,求和,sum,ret,next,链表,pCur,qCur
来源: https://www.cnblogs.com/syw-home/p/13914267.html