LeetCode OJ 2. Add Two Numbers

来源:互联网 发布:js获取当前页面url 编辑:程序博客网 时间:2024/06/05 10:15

题目大意

  给定两个链表,然后将对应位置相加,如遇对应位置相加结果超过10,向后进位。



public class Main {public static void main(String[] args) {// TODO Auto-generated method stubSolution ss = new Solution();ListNode head1 =  new ListNode(0);ListNode head2 =  new ListNode(0);int[] h1 = {2,4,3};int[] h2 = {5,6,4};ListNode p;p = head1;for(int i = 0;i < h1.length; i++){ListNode temp = new ListNode(h1[i]);p.next = temp;p = p.next;}/*p = head1.next;while(p != null){System.out.println(p.val);p = p.next;}*/p = head2;for(int i = 0;i < h2.length; i++){ListNode temp = new ListNode(h2[i]);p.next = temp;p = p.next;}System.out.println(ss.addTwoNumbers(head1, head2));p = ss.addTwoNumbers(head1, head2);while(p != null){System.out.println(p.val);p = p.next;}}}class ListNode {int val;ListNode next;ListNode(int x) { val = x; next = null;}}class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        ListNode sumhead = new ListNode(0);        ListNode p1 = l1,p2 = l2,p = sumhead;        int temp = 0;                        while(p1 != null || p2 != null){        if(p1 != null){        temp += p1.val;        p1 = p1.next;        }        if(p2 != null){        temp += p2.val;        p2 = p2.next;        }        p.next = new ListNode(temp%10);        p = p.next;        temp /= 10;        }        if(temp == 1)        p.next = new ListNode(1);        return sumhead.next;    }}


0 0
原创粉丝点击