利用数据栈来进行链表相加运算
定义两个栈接受链表的数据
stack1与stack2
在定义接收结果栈
stack
定义stack1与stack2出栈结果的和sum
sum需要满足十进制对10取余并
定义yuShu保存每一次相加的进位
在接下来的出栈中将
yuShu作为值加入运算
以此循环
最后得出结果栈
遍历加入链表
最后返回头节点
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ public ListNode addInList (ListNode head1, ListNode head2) { // write code here Stack<ListNode> stack1 = new Stack<ListNode>(); Stack<ListNode> stack2 = new Stack<ListNode>(); Stack<Integer> stack = new Stack<Integer>(); while(head1!=null){ stack1.add(head1); head1 = head1.next; } while(head2!=null){ stack2.add(head2); head2 = head2.next; } int sum,s1,s2; int yuShu=0; while(!stack1.isEmpty()){ s1 = stack1.pop().val; if(stack2.isEmpty()){ sum = (s1+yuShu)%10; yuShu=(s1+yuShu)/10; }else{ s2 = stack2.pop().val; sum = (s1+s2+yuShu)%10; yuShu = (s1+s2+yuShu)/10; } stack.add(sum); } while(!stack2.isEmpty()){ s2 = stack2.pop().val; sum = (s2+yuShu)%10; yuShu = (s2+yuShu)/10; stack.add(sum); } if(yuShu>0){ stack.add(yuShu); } if(stack.isEmpty()){ return null; } ListNode head=new ListNode(stack.pop()); ListNode temp = head; while(!stack.isEmpty()){ temp.next=new ListNode(stack.pop()); temp = temp.next; } return head; } }