首页 > 技术文章 > leetcode 题解 Add Two Numbers(两个单链表求和)

zhoutaotao 2014-07-03 23:00 原文

题目:

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

说明:

     1)和大数相加相似,数组换成单链表,注意单链表的操作,其他和大数求和方法相似:先对应为相加,再进行进位处理

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
12         ListNode head(-1);//头节点
13         ListNode *p1=l1;
14         ListNode *p2=l2;
15         ListNode *p=&head;
16         while(p1&&p2)//每个对应节点值相加
17         {
18             p1->val=(p1->val)+(p2->val);
19             p->next=p1;
20             p=p1;
21             p1=p1->next;
22             p2=p2->next;
23         }
24         p->next = p1?p1:p2;
25         int d=0;//进位值
26         p=head.next;
27         ListNode *q=NULL;
28         for(;p;q=p,p=p->next)//处理进位
29         {
30             
31             int a=(p->val)+d;
32             d=(a)/10;
33             p->val = (a)%10;
34         }
35         if(d>0) //最高位有进位,则新建一个节点,如果不new,则函数结束时内存会被释放掉
36         {
37             //ListNode *l3=new ListNode(d);
38             q->next=new ListNode(d);            
39         }
40         return l1;
41     }
42 };

 

推荐阅读