题解 | #链表相加(二)#

链表相加(二)

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

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */

    class Solution {
    public:
        /**
         * 
         * @param head1 ListNode类 
         * @param head2 ListNode类 
         * @return ListNode类
         */
              ListNode*reverseList(ListNode* s)
            {
                ListNode* nex = NULL;
                ListNode* pre = NULL;
                ListNode* cur = s;
                while(cur!=NULL)
                {
                   nex = cur->next;
                    cur->next = pre;
                    pre = cur;
                    cur = nex;
                }
                return pre;      
            }
        ListNode* addInList(ListNode* head1, ListNode* head2) {
            // write code here
             head1 = reverseList(head1);
            head2 = reverseList(head2);
            ListNode*tmp1 = head1;
            ListNode*tmp2 = head2;
            int n = 1;
            int m= 1;
            while(tmp1->next!=NULL)
            {
                tmp1 = tmp1->next;
                n++;        
            }
            while(tmp2->next!=NULL)
            {
                tmp2 = tmp2->next;
                m++;        
            }
            if(n>m)
            {
                for(int i = 0;i<(n-m);i++)
                {
                    tmp2->next = new ListNode(0);
                     tmp2 =tmp2->next;
                }    
            }
            else if(n<m)
            {
                 for(int i = 0;i<(m-n);i++)
                {
                    tmp1->next = new ListNode(0);
                    tmp1 = tmp1->next;
                }
            }
            int count = 0;
            int val = 0;
            ListNode* phead3 = new ListNode(-1);
            ListNode*w = phead3;
            ListNode*res = w;
            int nums = 0;
            while(head1!=NULL)
            {
                nums++;
                val = count+head1->val+head2->val;
                w->next = new ListNode(val%10);
                count = val/10;
                if(nums==1)
                {
                    res = w->next;
                }
                w = w->next;
                head1 = head1->next;
                head2 = head2->next;  
            }
            if(count>=1)
            {
                w->next = new ListNode(count);
                w=w->next;
            }
             head1 = reverseList(res);
            return head1;

        }
    };
全部评论

相关推荐

浪子陪都:简历最优秀的地方放到了后面,国奖,校级奖学金这些是最亮眼的。说明你跟同级别的学生不一样。 建议台灯这个,PCB布局布线这个词汇不专业,业内是PCB Layout,第二,单片机的板子一般不用考虑SI,PI 都是低速信号,只要遵循3W原则就好了。 单片机的项目太low了,技能这块,你要看一下BOSS直聘的招聘要求,按照别人的要求写,一些关键词可以增加你简历被检索到的概率。 主修课程不用写,这个没有人去关注的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务