LeetCode-Add Two Numbers-链表数字相加-链表操作+加法进位
https://oj.leetcode.com/problems/add-two-numbers/
跟大整数类似的链表操作。注意最后还有进位时需要再加入一个结点。
/** * 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) { if (l1==NULL) return l2; int up=0; ListNode *p=l1; ListNode *q=l2; ListNode *t=NULL; ListNode *h=NULL; while(p || q){ int vp=0,vq=0; if (p!=NULL){ vp=p->val; p=p->next; } else{vp=0;} if (q!=NULL){ vq=q->val; q=q->next; } else{vq=0;} int cur=vp+vq+up; up=cur/10; cur=cur%10; ListNode *cp= new ListNode(cur); if (t!=NULL) { t->next=cp; t=cp; } else{ t=cp; h=cp; } } if (up) { t->next=new ListNode(up); } return h; } };