文章目录
- 题目
- 方法一:借助一个进制位,以及更新尾结点
- 方法一改进:相比较第一种,给head一个临时头节点(开始节点),最后返回的时候返回head.next,这样可以省去第一次的判断
题目
方法一:借助一个进制位,以及更新尾结点
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode head = null;ListNode tail = null;int cay = 0;int n1 = 0;int n2 = 0;while(l1 != null || l2 != null){if(l1 == null) n1 = 0;else n1 = l1.val;if(l2 == null) n2 = 0;else n2 = l2.val;int sum = n1 + n2 + cay;if (head == null) head = tail = new ListNode(sum % 10);else {tail.next = new ListNode(sum % 10);tail = tail.next; }cay = sum /10 ;if(l1 != null) l1 = l1.next;if(l2 != null) l2 = l2.next;}if (cay == 1) { tail.next = new ListNode(1);tail.next.next = null;}return head;}
方法一改进:相比较第一种,给head一个临时头节点(开始节点),最后返回的时候返回head.next,这样可以省去第一次的判断
ListNode begin = new ListNode(1);
int sum = n1 + n2 + cay;tail.next = new ListNode(sum % 10);tail = tail.next; cay = sum /10 ;
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode begin = new ListNode(1);ListNode head = begin;ListNode tail = head;int cay = 0;int n1 = 0;int n2 = 0;while(l1 != null || l2 != null){if(l1 == null) n1 = 0;else n1 = l1.val;if(l2 == null) n2 = 0;else n2 = l2.val;int sum = n1 + n2 + cay;tail.next = new ListNode(sum % 10);tail = tail.next; cay = sum /10 ;if(l1 != null) l1 = l1.next;if(l2 != null) l2 = l2.next;}if (cay == 1) { tail.next = new ListNode(1);tail.next.next = null;}return head.next; }