using System; using System.Collections.Generic; /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ public ListNode addInList (ListNode head1, ListNode head2) { // write code here Stack<int> a=new Stack<int>(); Stack<int> b=new Stack<int>(); List<int> sum =new List<int>(); while(head1!=null) { a.Push(head1.val); head1=head1.next; } while(head2!=null) { b.Push(head2.val); head2=head2.next; } bool flag=false; while(a.Count>0 || b.Count>0) { int numA,numB; numA=a.Count==0?0:a.Pop(); numB=b.Count==0?0:b.Pop(); var add=numA+numB; add=flag?add+1:add; flag=add>=10; sum.Add(add%10); } if(flag) // 注意,相同长度链表的进位 sum.Add(1); ListNode tail=null; foreach(var s in sum) { ListNode head=new ListNode(s); head.next=tail; tail=head; } return tail; } }
因为链表长度不一致,所以如果是从个位开始,就可以双指针遍历,但高位在先,这里就利用栈这种数据结构,将值取出来,避免了手动编写逆序函数。
然后将栈顶的数两辆相加,这里要注意进位操作,以及一方先结束时,我这里用0补齐。最后从个位向前构造链表