NC40 两个链表生成相加链表

两个链表生成相加链表

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b?tpId=188&&tqId=38610&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking

NC40 两个链表生成相加链表

alt

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

class Solution {
public:
    /*
     1.翻转链表
     2.每一位相加
     3.相加之后%10,/10
     4.进位之后再相加
     */
    ListNode* ReverseList(ListNode* head){
        if(head == nullptr || head->next == nullptr)
            return head;
        ListNode* pre = head;
        ListNode* cur = head->next;
        ListNode* nx = cur->next;
        pre->next = nullptr;
        while(cur != nullptr){
            cur->next = pre;
            pre = cur;
            cur = nx;
            if(nx != nullptr)
                nx = nx->next;
        }
        head = pre;
        return head;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        head1 = ReverseList(head1);
	    head2 = ReverseList(head2);
	    int val = 0;
	    int n1 = 0, n2 = 0;
	    int val1 = 0, val2 = 0;
	    ListNode new_head(-1);
	    ListNode* cur = &new_head;

	    while (head1 != nullptr || head2 != nullptr)
	    {
	    	val1 = head1 == nullptr ? 0 : head1->val; 
	    	val2 = head2 == nullptr ? 0 : head2->val;
	    	
	    	val = val1 + val2 + n2;
	    	n1 = val % 10;
	    	n2 = val / 10;
	    	ListNode* new_node = new ListNode(n1);
	    	cur->next = new_node;
	    	cur = new_node;
	    	if (head1 != nullptr)
	    		head1 = head1->next;
	    	if (head2 != nullptr)
	    		head2 = head2->next;
	    }
	    if (n2 > 0)
	    {
	    	ListNode* new_node = new ListNode(n2);
	    	cur->next = new_node;
	    	cur = new_node;
	    }
	    ListNode* ans = ReverseList(new_head.next);
	    return ans;
    }
};
全部评论

相关推荐

求面试求offer啊啊啊啊:把华北改为华南再试一试,应该就没啥问题了。改完可能都不用投,别人主动联系了。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务