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

链表相加(二)

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:
    ListNode* reverse(ListNode* pHead) {
        ListNode* lst = nullptr;
        while (pHead) {
            ListNode* tmp = pHead -> next;
            pHead -> next = lst;
            lst = pHead;
            pHead = tmp;
        }
        return lst;
    }

    ListNode* addInList(ListNode* head1, ListNode* head2) {
        if (head1 == nullptr)  return head2;
        if (head2 == nullptr)  return head1;
        head1 = reverse(head1);
        head2 = reverse(head2);
        int cy = 0;
        int c1, c2, tmp;
        ListNode* lst = new ListNode(1);//将头节点设为1,如果最后进位为1就返回头节点,进位为0就返回第二个节点,不要头节点
        while (head1 || head2) {
            if (head1 && head2) {
                c1 = head1 -> val;
                c2 = head2 -> val;
                tmp = c1 + c2 + cy;
            } else if (head1) {
                c1 = head1 -> val;
                tmp = c1 + cy;

            } else if (head2) {
                c2 = head2 -> val;
                tmp = c2 + cy;
            }
            cy = tmp / 10;
            tmp = tmp % 10;
            ListNode* node = new ListNode(tmp);
            node -> next = lst -> next;//头插法,生成链表刚好是倒序
            lst -> next = node;
            if (head1) head1 = head1 -> next;
            if (head2) head2 = head2 -> next;
        }
        if(cy)
         return lst;
        return lst -> next;
    }
};

全部评论

相关推荐

“校招”、“3-5年经验”
xiaolihuam...:逆向工程不是搞外挂的吗,好像现在大学生坐牢最多的就是诈骗罪和非法侵入计算机系统罪,发美金,还居家办公,就是怕被一锅端,
点赞 评论 收藏
分享
点赞 评论 收藏
分享
程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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