Add Two Numbers

来源:互联网 发布:网络诈骗找谁 编辑:程序博客网 时间:2024/05/06 12:45
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
#include<iostream>using namespace std;//链表数据结构  struct ListNode{int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}ListNode(){}};//在链表末尾追加元素  void appendTail(ListNode **pHead, int val){ListNode *pNew = new ListNode();pNew->next = NULL;pNew->val = val;if (*pHead == NULL){*pHead = pNew;}else{ListNode *tmp = *pHead;while (tmp->next){tmp = tmp->next;}tmp->next = pNew;}}//正序输出链表  void show(ListNode *pHead){while (pHead){cout << pHead->val << " ";pHead = pHead->next;}cout << endl;}ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){ListNode *pNewHead = l1;bool isFlag = false;//是否产生进位//位数相同的相加while (l1 != NULL && l2 != NULL){int val = 0;if (isFlag){val = l1->val + l2->val + 1;}else{val = l1->val + l2->val;}if (val >= 10){l1->val = val - 10;isFlag = true;}else{l1->val = val;isFlag = false;}l1 = l1->next;l2 = l2->next;}//如果l1链表的表示的数字大while (l1){int val = l1->val;if (isFlag){val = l1->val + 1;}if (val >= 10){l1->val = val - 10;isFlag = true;}else{l1->val = val;isFlag = false;break;}l1 = l1->next;}ListNode *tmp = l2;//如果l2表示的数字大while (l2){int val = l2->val;if (isFlag){val = l2->val + 1;}if (val >= 10){l2->val = val - 10;isFlag = true;}else{isFlag = false;break;}l2 = l2->next;}ListNode *p = pNewHead;while (p->next){p = p->next;}p->next = tmp;if (isFlag){appendTail(&pNewHead, 1);}return pNewHead;}int main(void){ListNode *pHead1 = NULL;ListNode *pHead2 = NULL;appendTail(&pHead1, 9);appendTail(&pHead1, 8);appendTail(&pHead2, 1);ListNode *p1 = addTwoNumbers(pHead1, pHead2);show(p1);system("pause");return 0;}


0 0
原创粉丝点击