[C++]LeetCode 2: Add Two Numbers(链表逆序加法)

来源:互联网 发布:ubuntu 切换到命令行 编辑:程序博客网 时间:2024/05/22 07:50

Problem:

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


分析:

两输入链表本身为从低位到高位,故可直接利用加法式进行计算。注意设置链表头。

另若两链表为从高位到低位,可利用DFS深度搜索,利用stack栈来完成。


AC Code (C++) :

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode(int x) : val(x), next(NULL) {}* };*/class Solution {public://1555 / 1555 test cases passed.//Runtime: 53 msListNode* addTwoNumbers(ListNode* l1, ListNode* l2){if (l1 == NULL)return l2;if (l2 == NULL)return l1;//对应位相加int carry = 0;//进位ListNode pHead(-1);//链表头ListNode *pNode = &pHead;ListNode *pNode1 = l1;ListNode *pNode2 = l2;while (pNode1 != NULL || pNode2 != NULL){int sum = carry;if (pNode1 != NULL && pNode2 != NULL){sum = pNode1->val + pNode2->val + carry;pNode1 = pNode1->next;pNode2 = pNode2->next;}else if (pNode1 != NULL && pNode2 == NULL){sum = pNode1->val + carry;pNode1 = pNode1->next;}else if (pNode1 == NULL && pNode2 != NULL){sum = pNode2->val + carry;pNode2 = pNode2->next;}pNode->next = new ListNode(sum % 10);carry = sum / 10;pNode = pNode->next;}if (carry != 0){pNode->next = new ListNode(carry % 10);carry /= 10;pNode = pNode->next;}return pHead.next;}};


总结:

链表的使用,注意设置链表头

0 0