LeetCode_002

来源:互联网 发布:javascript插件 编辑:程序博客网 时间:2024/06/16 02:29

题目

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
  Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  Output: 7 -> 0 -> 8

题目解析

有两个单链表,代表两个非负数,每一个节点代表一个数位,数字是反向存储的,即第一个结点表示最低位,最后一个结点表示最高位。求两个数相加之后的和,并且以链表形式返回。

实现

public class Solution {     public static void main(String[] args){          int[] nums = {7,2,11,5,8,19};          ListNode list1 = new ListNode(2);          list1.next = new ListNode(4);          list1.next.next = new ListNode(3);          ListNode list2 = new ListNode(5);          list2.next = new ListNode(6);          list2.next.next = new ListNode(7);          list2.next.next.next = new ListNode(3);          ListNode result = addTwoNumbers(list1,list2);          while (result!=null){               System.out.print(result.value);               result = result.next;          }     }     /**      * 002-Add Two Numbers (单链表表示的两个数相加)      * @param list1 第一个数      * @param list2 第二个数      * @return 结果      */     public static ListNode addTwoNumbers(ListNode list1, ListNode list2) {          if (list1 == null) {               return list2;          }          if (list2 == null) {               return list1;          }          //声明两个指针 分别指向两个链表的头结点          ListNode pointer1 = list1;          ListNode pointer2 = list2;          // 新链表 储存结果          ListNode root = new ListNode(0);          ListNode pointer3 = root;          // 初始进位          int carry = 0;          int sum;          while (pointer1 != null && pointer2 != null) {               sum = pointer1.value + pointer2.value + carry;               // 本位的结果               ListNode node = new ListNode(sum % 10);               carry = sum / 10; // 本次进位               pointer3.next = node;               pointer3 = node;               pointer1 = pointer1.next;               pointer2 = pointer2.next;          }          if (pointer1 == null) {               pointer3.next = pointer2;          } else {               pointer3.next = pointer1;          }          // 最后一次相加还有进位          while (carry == 1 && pointer3.next!=null){               sum = carry+pointer3.next.value;               pointer3.next.value = sum%10;               carry = sum/10;               pointer3 = pointer3.next;          }          if(carry ==1){               ListNode node = new ListNode(1);               pointer3.next = node;          }          return root.next;     }}class ListNode{     int value;     ListNode next;     public ListNode(int value,ListNode node){          this.value = value;          this.next = node;     }     public ListNode(int value){          this.value = value;     }}