【LeetCode练习题】Add Two Numbers

链表相加

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 

题目意思:

给定两个链表,返回其相加的结果。注意链表是倒序的,即第一个节点是个位。

 

解题思路:

这个有点类似于大数加法,只不过大数加法用的是vector,可以求出长度,而链表则不行,而且链表还要小心空指针。

加法过程就是小学加法的那个过程,对应位相加并且加上上一位的进制。因为链表长短不一,所以当某一个链表结束而另外一个没结束时,需要让没结束的那个链表的每个节点继续和0相加即可。

这题没什么难度哈……

 

代码如下:

 

 1 class Solution {

 2 public:

 3     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {

 4         if(!l1)

 5             return l2;

 6         if(!l2)

 7             return l1;

 8 

 9         ListNode *head = new ListNode(0);

10         ListNode *ret = head;

11         ListNode *p = head;

12         int nCarry = 0;

13 

14         while(l1 && l2){

15             int a = l1->val;

16             int b = l2->val;

17             int c = a + b + nCarry;

18             nCarry = c / 10;

19             // c % 10 new node

20             p->next = new ListNode(c%10);

21             p = p->next;

22             l1 = l1->next;

23             l2 = l2->next;

24         }

25         //当l1还有剩余时,用l1里的节点继续和0加

26         while(l1){

27             int a = l1->val;

28             int b = 0;

29             int c = a + b + nCarry;

30             nCarry = c / 10;

31             p->next = new ListNode(c%10);

32             p = p->next;

33             l1 = l1->next;

34         }

35         //当l2还有剩余时,用l2里的节点继续和0加

36         while(l2){

37             int a = l2->val;

38             int b = 0;

39             int c = a + b + nCarry;

40             nCarry = c / 10;

41             p->next = new ListNode(c%10);

42             p = p->next;

43             l2 = l2->next;

44         }

45         //类似于 1 -> 9和 2 -> 1相加这种,需要新加一个值为1的节点。

46         if(nCarry){

47             p->next = new ListNode(1);

48             nCarry = 0;

49         }

50         ret = ret->next;

51         delete head;

52         return ret;

53     }

54 };

 

你可能感兴趣的:(LeetCode)