LeetCode2. Add Two Numbers (链表操作)

题目大意:给定两个列表,将它们逆序求和,输出和。题目中规定中列表中的每个数都是非负,并且都是个位数。

题目分析:本题题目要求要用链表来操作,值得注意的是两个列表非等长的情况。

由于我是刚开始刷LeetCode的题,所以对于编程环境还不太熟悉,在LeetCode中一些数据结构会实现给定好,不需要我们自己创建,例如本题中的结构体ListNode,这里要对指针、链表的基本操作有一个了解。

首先,声明一个head头结点,初始值为0,然后再创建一个list指针指向头结点。这里为什么不直接创建ListNode * list = new ListNode(0)? 因为head指针有作用,需要在函数结束时返回head->next,表示第一个元素。在程序中,移动的一直是list指针、l1指针、l2指针,head一直是没有动的。当有进位时,需要把进位算到下一次计算中。在最后如果最高位有进位,也要产生新节点,将指针后移,比如,5+5=10,需要进位1.

代码展示:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int temp = 0;
        ListNode* head = new ListNode(0);
        ListNode* list = head;
        while(l1!=NULL || l2!=NULL){
            if(l1!=NULL){
                temp += l1->val;
                l1 = l1->next;
            }
            if(l2!=NULL){
                temp += l2->val;
                l2 = l2->next;
            }
            list->next = new ListNode(temp%10);
            list = list->next;
            temp /= 10;
        }
        if(temp!=0){
            list->next = new ListNode(temp);
        }
        return head->next;
    }
};

猜你喜欢

转载自blog.csdn.net/jaster_wisdom/article/details/79807788