本文共 3235 字,大约阅读时间需要 10 分钟。
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)输出: 7 -> 8 -> 0 -> 7
思路+代码+注释:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { StackstackOne=new Stack<>(); Stack stackTwo=new Stack<>(); ListNode next=null; ListNode cur=null; while (l1!=null) { stackOne.add(l1); l1=l1.next; } while (l2!=null) { stackTwo.add(l2); l2=l2.next; } while (stackOne.size()>0 && stackTwo.size()>0) { ListNode nodeOne=stackOne.pop(); ListNode nodeTwo=stackTwo.pop(); int sum=nodeOne.val+nodeTwo.val; if (sum>9) { if (stackOne.size()==0 && stackTwo.size()==0) { cur=new ListNode(sum-10); ListNode head=new ListNode(1); cur.next=next; head.next=cur; return head; } if (stackOne.size()>0) { cur=new ListNode(sum-10); cur.next=next; ListNode n1=stackOne.peek(); n1.val=n1.val+1; }else { cur=new ListNode(sum-10); cur.next=next; ListNode n1=stackTwo.peek(); n1.val=n1.val+1; } next=cur; } else { cur=new ListNode(sum); cur.next=next; next=cur; } } while (stackOne.size()>0) { cur=stackOne.pop(); if (cur.val>9) { int cha=cur.val-10; if (stackOne.size()>0) { stackOne.peek().val=stackOne.peek().val+1; cur=new ListNode(cha); }else { cur=new ListNode(cha); ListNode head=new ListNode(1); cur.next=next; head.next=cur; return head; } } cur.next=next; next=cur; } while (stackTwo.size()>0) { cur=stackTwo.pop(); if (cur.val>9) { int cha=cur.val-10; if (stackTwo.size()>0) { stackTwo.peek().val=stackTwo.peek().val+1; cur=new ListNode(cha); }else { cur=new ListNode(cha); ListNode head=new ListNode(1); cur.next=next; head.next=cur; return head; } } cur.next=next; next=cur; } return cur; }
转载地址:http://mvwa.baihongyu.com/