leetcode原题为第445. 两数相加 II 高位存储在链表头结点,思路:将两数都存到栈里,然后在分别出栈相加即是对应位的相加再存到链表里
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { Stack<Integer> stack1=new Stack();//栈的创建 Stack<Integer> stack2=new Stack(); ListNode sum=new ListNode(0); ListNode p1=l1,p2=l2,p3=sum; while(l1!=null){ stack1.push(l1.val); l1=l1.next; } while(l2!=null){ stack2.push(l2.val);//压栈 l2=l2.next; } ListNode head=null; int flag=0; int value=0; while(!stack1.isEmpty() || !stack2.isEmpty() || flag!=0){ if(!stack1.isEmpty()) value+=stack1.pop();//出栈 if(!stack2.isEmpty()) value+=stack2.pop(); value+=flag; ListNode p=new ListNode(value%10); flag=value/10; p.next=head; //注意这里相当于是head和p互换了位置,即head总指向新进来的节点 head=p; value=0; } return head; } }
leetcode原题为第2. 两数相加 思路:高位存储在链表末尾,按顺序相加,然后放到新的链表里即可
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode sum=new ListNode(0); ListNode p1=l1,p2=l2,p3=sum; int flag=0; while(p1!=null || p2!=null || flag!=0){ int value=0; if(p1!=null){ value+=p1.val; p1=p1.next; } if(p2!=null){ value+=p2.val; p2=p2.next; } value+=flag; p3.next=new ListNode(value%10);//将p3当做一个指针 p3=p3.next; flag=value/10; } return sum.next; } }