题解 | #两个链表生成相加链表#

两个链表生成相加链表

http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

题意:
        假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
        给定两个这种链表,请生成代表两个整数相加值的结果链表。
方法:
模拟

思路:
        首先,反转给定的两个链表,使之右对齐;
        然后,初始化双指针遍历链表相加,并得到结果链表;
        最后,将结果链表反转即可。

        

class Solution {
public:
    
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        head1=reverseList(head1);//反转链表
        head2=reverseList(head2);
        
        ListNode *p=head1,*q=head2;//初始化
        ListNode *head=nullptr,*tail,*t;
        int flag=0;//进位标志
        while(p||q){
            //加法
            int temp=flag;
            if(p){
                temp+=p->val;
                p=p->next;
            }
            if(q){
                temp+=q->val;
                q=q->next;
            }
            if(temp>9){//判断进位
                flag=1;
                temp%=10;
            }else{
                flag=0;
            }
            t=new ListNode(temp);//新建节点
            if(head==nullptr){//插入节点
                head=t;
            }else{
                tail->next=t;
            }
            tail=t;
        }
        if(flag){//最后判断进位
            t=new ListNode(1);
            if(head==nullptr){
                head=t;
            }else{
                tail->next=t;
            }
            tail=t;
        }
        return reverseList(head);//反转答案链表
    }
    
    ListNode* reverseList(ListNode* head){//反转链表
        if(head==nullptr)
            return head;
        ListNode *p=head,*q=head->next,*t;//初始化
        p->next=nullptr;
        while(q){//反转操作
            t=q->next;
            q->next=p;
            p=q;
            q=t;
        }
        return p;
    }
};

时间复杂度:
空间复杂度:

全部评论

相关推荐

一表renzha:不是你说是南通我都没往那方面想,人家真是想表达那个意思吗?
点赞 评论 收藏
分享
07-02 22:46
门头沟学院 Java
码农索隆:hr:“管你投没投,先挂了再说”
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务