算法题---链表求和

 

 

 

// 链表求和
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;
}

 

posted @ 2020-11-02 14:28  威威后花园  阅读(100)  评论(0编辑  收藏  举报