链表:链表两数相加( LeetCode 2. Add Two Numbers(两数相加))

原题网址:https://leetcode.com/problems/add-two-numbers/

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

看了很多文章,都没有编译通过,最近在学算法,看了小象学院邹博的课程,于是想总结一下。代码如下,给定了两个链表输入,一个长度为6,一个长度为9。


#include

#include

using namespacestd;


typedef struct tagSNode   //tagSNode是结构标签,后续的声明可写为struct tagSNode x;

{

    int value;

    tagSNode* pNext;

    tagSNode(int v):value(v),pNext(NULL){}

}SNode;                   //SNode是类型名,后续的声明可写为SNode x;


SNode* Add(SNode* pHead1,SNode* pHead2)

{

    SNode* pSum =new SNode(0);

    SNode* pTail = pSum; //新结点插入到pTail的后边

    SNode* p1 = pHead1->pNext;

    SNode* p2 = pHead2->pNext;

    SNode* pCur;

    int carry =0;   //进位

    int value;

    while (p1&&p2) {

        value = p1->value + p2->value +carry;

        carry = value/10;

        value %=10;

        pCur = newSNode(value);

        pTail->pNext = pCur;

        pTail = pCur;

        

        p1 = p1->pNext;

        p2 = p2->pNext;

    }

    

    //处理较长的链

    SNode *p=p1 ? p1:p2;

    while (p) {

        value=p->value+carry;

        carry = value/10;

        value%=10;

        pCur = newSNode(value);

        pTail->pNext = pCur;

        pTail = pCur;

        p=p->pNext;

    }

    

    //处理可能存在的进位

    if (carry!=0) {

        pTail->pNext =new SNode(carry);

    }

    return pSum;

}

//销毁链表

void Destroy(SNode* p)

{

    SNode* next;

    while (p) {

        next = p->pNext;

        delete p;

        p=next;

    }

}

//打印链表

void Print(SNode* p)

{

    while (p->pNext) {

        printf("%d->",p->value);

        p=p->pNext;

    }

    printf("%d\n",p->value);

}


int main()

{

    SNode* pHead1 =new SNode(0);

    int i;

    for (i=0; i<6; i++) {

        SNode* p =new SNode(rand() %10);

        p->pNext = pHead1->pNext;

        pHead1->pNext=p;

    }

    

    SNode* pHead2 =new SNode(0);

    for (i=0; i<9; i++) {

        SNode* p =new SNode(rand()%10);

        p->pNext = pHead2->pNext;

        pHead2->pNext=p;

    }

    

    Print(pHead1);

    Print(pHead2);

    SNode *pSum =Add(pHead1,pHead2);

    Print(pSum);

    Destroy(pHead1);

    Destroy(pHead2);

    Destroy(pSum);

    return0;

}


你可能感兴趣的:(面试算法)